Through the previous study. We will feel that for a large project with more beans, the configuration of spring will be more complex.
Then we'll show you how to simplify the spring configuration.
The simplified spring configuration is divided into two main categories:
1. Take the initiative to assemble yourself
2. Proactively scan yourself
Here's how these two simplified configurations are described in detail.
Self-assembling the type of the active assembly
- ByName: Self-assembling according to the name of the property
- Bytype: Self-assembling according to the type of the property
- Constructor: Self-assembling according to the type of the constructor
- AutoDetect: The best self-assembly. First, the use of constructor self-assembly, if not found with the constructor matching beans, using Bytype to carry out their own active assembly.
Implement your own active assembly using XML
- ByName: Assembly based on the name of the attribute
Add the attribute autowire= "ByName" to the bean tag. When spring starts, it looks for a bean with the same name as the member variable in person, and the bean is injected to the member variable of person.
<bean id="person" class="com.njupt.Person" autowire="byName"> </bean>
- Bytype: Assembling according to the type of the attribute
Add the attribute autowire= "ByName" to the bean tag.When spring starts, it looks for the same bean as the member variable type in person. And the bean is injected to the member variable of person.
<bean id="person" class="com.njupt.Person" autowire="byType"> </bean>
Disadvantages of Bytype: Suppose that a bean of a certain type has more than one. Spring throws an exception when it looks for a bean of the same type through Bytype.
How to resolve:
-Set whether the same type of bean is preferred
In the bean that needs to be preferred, such as the following settings:
<bean id="person" class="com.njupt.Person" primary="true"> </bean>
In the bean that does not need to be preferred, such as the following settings:
<bean id="person" class="com.njupt.Person" primary="false"> </bean>
- Cancel the candidacy of some of the same types of beans
Use the Auto-candidate property to cancel the candidacy of some beans. Spring excludes these beans directly when looking for the same type of bean for the property.
<bean id="person" class="com.njupt.Person" default-candidate="false"> </bean>
- Constructor: Assembly According to the type of the constructor's parameters
When Autowire is set to constructor, spring looks for the same bean as the constructor's parameter type and injects it into the constructor.
<bean id="person" class="com.njupt.Person" autowire="constructor"> </bean>
The constructor's own active assembly is still essentially assembled by Bytype, just autowire= "constructor". Spring will make its own active assembly of the constructor's parameters. When autowire= "Bytype", Spring makes its own active assembly of the Bean's member variables.
The constructor's own active assembly and Bytype own active assembly have the same disadvantage: when a bean of a certain type has multiple, spring cannot determine which bean to choose, and throws an exception directly.
In addition The constructor's own active Assembly also has a unique drawback: when there are multiple constructors, spring cannot choose exactly which constructor to initialize, so it also runs out of the exception.
- AutoDetect: The best self-assembly.
When spring Initializes a bean with the autowire= "AutoDetect" set, it is first assembled with a constructor. If there are multiple beans or constructors that match the constructor, the attributes are assembled using Bytype.
Use the default own active assembly
The above self-assembled approach is for a single bean, assuming that all beans under beans use some kind of self-active assembly strategy, then add the following configuration to the beans tag, for example:
default-autowire="byType"
- Note 1: After Default-autowire has been set in beans. This parameter is valid only for the bean between the current beans tags.
- Note 2: Use the default self-assembly after the initiative. You can still set your own active assembly policy in the bean, and the Bean's own active assembly policy overrides the default policy.
- Note 3: After using your own active assembly, we are still able to display and assemble the bean in the bean through the Constructor-arg property and property properties.
such a mix of display assembly and self-assembly can successfully solve the uncertainty problem of Bytype .
- Note 4: If you use constructor to implement your own active assembly of constructor parameters, you cannot mix the autowire= "constructor" property with the Constructor-arg label.
Use annotations to implement your own active assembly
Using annotation assembly is actually moving the autowire= "xxx" attribute from the bean in the original XML into the Java code of the Bean class. There is no difference in function.
Here's how to use annotations to implement your own active assembly.
1. Open the annotations to self-assemble
For example, the following configuration is done in beans:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.5.xsd"> <context:annotation-config></beans>
2. Use @autowired to annotate functions or properties that need to be actively assembled
When a property in a bean, a function is marked @autowired. When spring creates the object of this bean, it uses Bytype to find its own active assembly with the same type of bean as the attributes and function parameters.
-Labeling constructors with @autowired
@Autowired publicPerson(String name,long id){ this.name = name; this.id = id; }
- Labeling common functions with @autowired
@Autowired publicvoidcreateInstance(){ System.out.println("对象被创建啦!"); }
- Labeling attributes with @autowired
@Autowired private Father father;
@Autowired essentially uses Bytype for its own active assembly. So there is the same problem as Bytype: If a bean of the same type has more than one, or the bean of that type cannot be found. Spring throws an exception.
Coping Strategies of @Autowired Malpractice
- If a bean of the same type has more than one
Use XML to set the bean's own active assembly. You can use the display assembly method. Manually set the parameters that need to be injected, while using annotations to self-assemble, you can use @qualifier to narrow the range of candidate beans. Specific actions such as the following:
@Autowired @Qualifier("father") private Father father;
The @Qualifier ("id") is assembled father based on the Bean's ID.
- If a bean of a certain type cannot be found
Assuming that some of the attributes in the bean and the parameters are not required to initialize the value, then add the required attribute to the @autowired of the attribute or the parameter:
@Autowired(required="false") publicPerson(String name,long id){ this.name = name; this.id = id; }
At this point, it is assumed that spring cannot find a bean of the same type as the constructor's parameter, and it is null.
Note: If a bean has more than one constructor. Only one constructor can be set to @autowired (Required=true), and the rest of the constructors can only be set to @autowired (Required=false)
Using Spel expressions in annotations
By learning from the previous we know that in spring's XML configuration, you can use Spel expressions to implement manual assembly. Similarly, you can use Spel expressions to implement manual assembly in annotations.
-Inject a bean named father to the constructor:
@Value("#{father}") publicPerson(Father father){ this.father = father; }
- Inject the ID from the Father object to the ID:
@Value("#{father.id}") publicvoidsetId(long id){ this.id = id; }
Take the initiative to detect
Self-assembly can reduce the number of property labels and Constructor-arg labels under the bean tag. Self-checking can reduce the number of bean labels.
1. Open spring's own active test
The waist to open its own active detection function, you need to do in the XML beans tag such as the following configuration:
-Base-package: Represents the package to be scanned
< Beans xmlns = "http://www.springframework.org /schema/beans " xmlns:xsi =" http://www.w3.org /2001/xmlschema-instance " xsi:schemalocation = "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans-4.5.xsd "; <context: Component-scan base-package = "com.xxx" ; </context:component-scan > </beans ;
2. Add @component annotations for beans that need to be actively reduced
To make a Java class into a bean. You need to add @component annotations to the class.
Spring starts by looking for classes that are @component tagged under the package specified by Base-package and initializes them to beans. Saved in the Springcontext.
-type small writing as the Bean's name:
@Componentclass Person{}
- Specify the name of the bean:
@Component("person")class Person{}
3. Filter the scanned bean to replace the XML configuration with Java
Although the use of annotations has greatly reduced the XML configuration in spring, but still requires a small amount of XML configuration, we are able to implement the XML configuration in Java code, thus completely avoiding the XML configuration.
1. Define a Spring configuration class
Label a class with the @configuration tag to indicate that the class is a spring configuration class:
@Comfigurationclass Person{ ……}
2. Declaring a Bean
In spring's configuration class, a bean is labeled with the @bean tag.
-Function name: Bean ID
-Return value: type of bean
-Body of the function: Initialize the bean
@Comfigurationclass Person{ @Bean publicperson(){ //构造器注入 new Person("柴毛毛"); //属性注入 person.setAge(22); return person; }}
3. Using Java for Injection
In the Java configuration of spring, the injection of bean properties and constructors is easy, just to operate in the function:
@Comfigurationclass Person{ @Bean publicperson(){ returnnew Person(); }}
Advantages of using Java to replace XML configuration
In the XML configuration. The type of the bean is expressed in string. So there is only the ability to find out if the bean type is wrong in the execution of the node, and in the Java configuration, the type of the bean is found to be wrong during the compilation phase. So as to be able to find errors early.
Follow Chai Maomau to learn Spring (3)--Simplify bean configuration