Spring Abstract bean and inheritance

Source: Internet
Author: User
Tags abstract chop constructor inheritance

Transferred from: http://ronxin999.blog.163.com/blog/static/4221792020116911527847/

When we apply spring, we are sure to use abstract classes in general design. So how do you configure these abstract beans in spring? Please see below:

If the configuration information between the two beans is very similar, inheritance can be used to reduce the duplication of configuration work.
Inheritance refers to a child bean definition that inherits some of the configuration information from the parent bean definition, or overrides a specific configuration letter
Or add a few configurations. Using inheritance configuration can save a lot of configuration work. In practical applications, the general
The configuration is configured as a template that can be inherited by the child bean.

using the abstract property

As described earlier, the generic configuration is configured as a template, and the template does not need to be instantiated, only as a template defined by the child bean. ApplicationContext, by default, pre-initializes all singleton beans. Using the abstract property, you can prevent the template bean from being pre-initialized.
A bean with the abstract property of true is called an abstraction bean, and the container ignores all abstract bean definitions and does not initialize the abstract bean when it is pre-initialized.
If the abstract property is not defined, the property defaults to False. The following configuration file defines an abstract bean, which is used as a template:

public class Steelaxe implements Axe
{
Count is a status value that increases by 1 per execution of the Chop method
private int count = 0;
Public Steelaxe () {
System.out.println ("Spring instantiation relies on bean:steelaxe instances ...");
}
Test methods
Public String Chop () {
Return "Steel axe chopping wood really fast" + ++count;
}
}

Public class Chinese implements person
Programming for axe interfaces, not specific implementation classes
Private Axe Axe;
The default constructor
Public Chinese () {
System.out.println ("Spring instantiation of the keynote Bean:chinese instance ... ");
}
Setter method required to set value injection
public void Setaxe (Axe Axe) {
SYSTEM.OUT.PR ntln ("Spring Execution Dependency Injection ...");
This.axe = axe;
}
Useaxe method for implementing the person interface
public void Useaxe () {
System.out.println (Axe.chop ());
}
}

<?xml version= "1.0" encoding= "gb2312"?>
<! a dtd> that specifies the spring configuration file
<ldoctype Beans Publ Industrial C "-//spring//dtd bean//en"
' Http://www.springframework.org/dtd/spring-beans.dtd ' >
<! the root element of a spring configuration file
<beans>
<bean id= "Steelaxe" class= "Lee. Steelaxe "/>
<!... Defining the bean through the abstract attribute is abstract bean-->
<bean id= "Chinesetemplate" class= "Lee. Chinese "abstract=" true ">
<! A property that defines a dependency injection)
<property name= "Axe" >
<ref local= "Steelaxe"/>
</property>
</bean>
</beans>
As can be seen from the configuration file, the definition of an abstract bean is almost indistinguishable from the definition of a normal bean, only increasing the abstract property to True,
However, there are significant differences in the results of the main program execution. The following main program uses Appliactioncontext as the spring container,
. Appliationcontext Default Pre-initializes all singleton beans. The main program section is as follows:

public class Beantest
{
public static void Main (string[] args) throws exception{
ApplicationContext CTX = new Filesysternxmlapplicationcontext ("Bean.xml");
}
}
The main program section only instantiates ApplicationContext, and when instantiating ApplicationContext, the singleton bean is instantiated by default.
The results of the program execution are as follows:

Spring instantiates dependent Bean:steelaxe instances: .

The container does not instantiate the chinesetemplate bean, but ignores all Beano that are declared abstract if the abstract attribute definition is canceled,
The program execution results are as follows:

Spring instantiation relies on Bean:steelaxe real ~j ...
Spring instantiation of the keynote Bean:chinese instance: .
Spring Execution Dependency Injection ...

As you can see, an abstract bean is a bean template, and the container ignores the abstract bean definition, so the abstract bean is not instantiated.
Abstract beans, however, do not need to be instantiated, so there is no class attribute. The following configuration files are also valid:
<?xml version= "1.0" E-Port coding= "gb2312"?>
<! a dtd> that specifies the spring configuration file
<! DOCTYPE Beans Public "-/! SPRING//DTD bean//en "
"Http://www.springframework.org/dtd/spring-beans.dtd" >
<! --The root element of the Spring configuration file--
<beans>
<bean id= "Steelaxe" class= "Lee. Steelaxe "/>
<! The bean is an abstract bean that is defined by the abstract property, and the abstraction bean does not specify a class attribute.
<bean id= "Chinesetemplate" abstract= "true" >
<!... Defining the attribute of a dependency injection
<property name= "Axe" >
<ref local= "Steelaxe"/>
</property>
</bean〉
</beans>

Note: Abstract beans cannot be instantiated, can neither get abstract beans through getbean, nor let other beans
The value of the ref attribute points to an abstract bean, so as long as an attempt to instantiate the abstract bean will result in an error


Defining child Beans

We refer to the bean that specifies the value of the parent property as a child bean; The parent pointer to the child bean's template, referred to as the Father Bean.
The child bean can inherit the implementation class, constructor parameters, and property values from the parent bean, or add new values. If a init-method is specified,
Destroy-method and Factory-method Properties, they overwrite the definition of the parent bean. Child Bean cannot be from parent bean
Inherit the following properties: Depends-on, Autowire, Dependency-check,singleton, Lazy-init. These properties are derived from the child bean definition,
Or take the default value. By setting the Parent property to define a child bean, the Parent property value is the parental bean ID. Modify the above configuration text
Add the sub-bean definition as follows:
<?xml version= "1.0" encoding= "gb2312"?>
<! a dtd> that specifies the spring configuration file
<ldoctype Beans Publ Industrial C "-//spring//dtd bean//en"
' Http://www.springframework.org/dtd/spring-beans.dtd ' >
<!--the root element of a Spring configuration file)
<beans>
<bean id= "Steelaxe" class= "Lee. Steelaxe "/>
<! a bean that is defined through the abstract attribute is abstract bean-->
<bean id= "Chinesetemplate" class= "Lee. Chinese "abstract=" true ">
<!--defining the attribute of a dependency injection)
<property name= "Axe" >
<ref local= "Steelaxe"/>
</property>
</bean>
<! define a child bean through the parent property?
<bean id= "Chinese" parent= "chinesetemplate"/>
</beans>
The definition of a child bean is not much different from a normal bean, only the Parent property is added. A child bean can have no class attribute,
If there is a class attribute in the parent bean definition, its class attribute can be omitted from the child bean definition, but the child bean will take the same implementation class as the parent bean.
The test program is modified as follows:
public class Beantest
{
public static void Main (string[] args) throws exception{
ApplicationContext CTX = new Filesysternxmlapplicationcontext ("Bean.xml");
Person P = (person) ctx.getbean ("Chinese");
P.useaxe (); }
}
The results of the program execution are as follows:
Spring instantiates dependent Bean:stee1axe instances: .
Spring instantiation of the keynote Bean:chinese instance: .
Spring Execution Dependency Injection ...
Steel axe chopping wood really fast

In addition, the child bean inherits the implementation class from the parent bean definition and relies on the bean. But the child bean can also overwrite the definition of the parent bean, looking at the following configuration file:

The AXE implementation class Stoneaxe is as follows:
public class Stoneaxe implements Axe
Default constructor
Public Stoneaxe () {
System.out.println ("Spring instantiation relies on bean:stoneaxe instances ..."); }
The chop method of implementing Axe interface
Public String Chop () {
Return "stone axe chopping wood is very slow";
}
}

The Chinese sub-categories are as follows:
Public class Shanghai extends Chinese {

public void Show () {
System.out.println ("Sub-bean, Shanghai, China");
}

}


&LT;?XM1 version= "1.0" encoding= "gb2312"?>
<! Specify the dtd> of the spring configuration file
<ldoctype beans Public "-//spring//dtd bean//en"
' Http://www.springframework.org/dtd/spring-beans.dtd ' >
<! --The root element of the Spring configuration file
<beans>
<bean id= "Steelaxe" class= "Lee. Steelaxe "/>
<bean id= "Stoneaxe" class= "Lee. Stoneaxe "/>
<! a bean that is defined through the abstract attribute is abstract bean-->
<bean id= "Chinesetemplate" class= "Lee. Chinese "abstract=" true ">
<property name= "Axe" >
<ref local= "Steelaxe"/>
</property>
</bean>
<! defines a child bean--> through the Parent property
<bean id= "Shanghai" parent= "Chinesetemplate" >
<! a dependency definition that overrides a parent bean ...
<property name= "Axe" >
<ref local= "Stoneaxe"/>
</property>
</bean>
</beans>

At this point, the child Bean's dependency is no longer dependent on the parent bean definition.Note that this time the father of the class Lee. Chinese cannot be an abstract class, (described below: abstract= "true") does not necessarily mean that the class must be an abstract class, not an abstract class can also be defined in spring as an abstract bean, if your class is an abstract class, You can't use the parent Bean's class at this time, so be sure to define class in the child bean to initialize the child bean.
The test program is modified as follows:
public class Beantest
{
public static void Main (string[] args) throws exception{
ApplicationContext CTX = new Filesysternxmlapplicationcontext ("Bean.xml");
Person P = (person) ctx.getbean ("Shanghai");
P.useaxe (); }

}

Follow the results of the above test program as follows:
Spring instantiates dependent Bean:steelaxe instances: .
Spring instantiates dependent Bean:stoneaxe instances: .
Spring instantiation of the keynote Bean:chinese instance: .
Spring Execution Dependency Injection ...
The stone axe is very slow to chop

Note: The child bean definitions in the previous example do not have a class property, because the class attribute is already in the parent bean definition, and the child Bean's class attribute can inherit from the parent bean definition, but it is important to note that the parent bean must not be an abstract class when inheriting the class from the parent bean. , because an abstract class cannot create an instance, and if the class attribute is not specified in the parent bean definition, the class attribute must be specified in the child bean definition, otherwise an error occurs; If the parent bean definition Specifies the class attribute and the child Bean definition also specifies the class attribute, the child bean Overrides the defined class attribute to the class attribute defined by the parent bean.

-------------------------------------------------------------------------------------

---------------------------------------------------

The inheritance of beans in Spring is very different from the inheritance in Java, which is the continuation of the arguments between the instance and the instance, which is the general to the special refinement, the former is the relationship between the object and the object, the latter is the relationship between the class and the class.

Child beans and parent beans in a.spring can be of different types, but in Java inheritance, subclasses are a special kind of parent class;

The inheritance of the bean in b.spring is the relationship between the instances, mainly manifested in the continuation of the parameters, while the inheritance in Java is the relationship between class and class, mainly embodied in the continuation of methods and attributes.

C.spring neutron beans cannot be used as parent beans and are not polymorphic, and subclass instances in Java can be used entirely as instances of the parent class.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.