1. Spring configuration overview
1.1. Overview
Spring container reads bean configuration information from xml configuration, java annotation, and spring annotation to form a bean definition registry;
Define the registry to instantiate the bean according to the bean;
Put bean instances into bean cache pool;
The application uses beans.
1.2. XML-based configuration
(1) Overview of xml file
xmlns---------------------------------------------------------------------------------------------------------------------------
xmlns:xsi------------Standard namespace, used to specify the schema file of the custom namespace
xmlns:xxx="aaaaa"------------Custom namespace, xxx is an alias, and the following value aaaa is the full name
xsi:schemaLocation--------Specify a specific schema file for each namespace, format: the namespace full name file address. . . Separate with spaces
2. Basic Bean configuration
2.1. Naming of Bean
(1) Both id and name can specify multiple names, and the names are separated by commas, semicolons or spaces.
<beanname="#car,123,$car"class="xxxxxxxxx">
Users can use getBean("#car"), getBean("123"), getBean("$car") to getbean.
(2) If no id and name attributes are specified, spring will automatically use the fully qualified name of the class as the name of the bean
(3) If there are multiple anonymous beans, that is, there is no <bean/> with id and name specified, assuming that the fully qualified name of the class is xxx.
Then get the first bean using getBean("xxx"), get the second bean using getBean("xxx#1"), get the third bean using getBean("xxx#2").
3. Dependency injection
3.1. Attribute injection
(1) Attribute injection requires the Bean to provide a default constructor and provide a Setter method for the attributes that need to be injected. Spring calls the default constructor to instantiate the bean object, and then calls the Setter method to inject the property value through reflection.
(2) Spring will only check whether there is a corresponding Setter method in the bean, and no requirements will be made as to whether there is a corresponding attribute variable in the bean.
(3) Javabean's special specifications for attribute naming: the first 2 letters of a variable are either all uppercase or all lowercase.
3.2. Constructor Injection
(1) The configuration order of constructor parameters will not affect the configuration results. The configuration file of spring adopts a policy that is unrelated to the order of element labels. This strategy can ensure the certainty of configuration information to a certain extent.
(2) Match parameters by index
If the constructor's entry parameter type is the same, you need to specify the sequential index of the parameters, otherwise the corresponding relationship cannot be determined. like:
<constructor-argindex="0"value="xxxxxx"><constructor-argindex="1"value="xxxxxx">
The index starts at 0.
(3) Circular dependency problem
If the constructor configuration of 2 beans depends on the other party, a thread deadlock problem will occur.
The solution is to change the constructor injection to attribute injection.
3.3. Factory method injection
(1) Non-static factory method
Since the factory method is not static, you must first create an instance bean of the factory class and use factory-bean to reference it
<beanid="carFactory"class="factory class"/><beanid="car5"factory-bean="carFactory"factory-method="createCar"/>
(2) Static factory method
<beanid="car5"class="factory class"factory-method="createCar"/>
3.4. Detailed explanation of the injection parameters
(1) 5 special characters in xml
| Special symbols | Escape sequence | Special symbols | Escape sequence |
| < | < | "" | |
| > | > | ' | ' |
| & | & |
(2)<![CDATA[]]>
The purpose of <![CDATA[]]> is to let the XML parser treat the string in the tag as normal text.
(3) Inject null value using the <null/> tag
(4) Cascading attributes
<beanid="parent"class="xxxxxxx"><propertyname="child.xxx"value="Property value of dependency object"/></bean>
Before spring3.0, the dependency object child must be instantiated first, otherwise an exception will be thrown. After spring3.0, there is no need to display instantiation. The spring container will automatically instantiate the dependency object.
(5) Collection merge
<setmerge="true"/>
Commonly used in subclasses to merge collection elements of parent class
(6) Configure collection type beans through the util namespace
If you want to configure a collection type bean instead of a collection type property, you can configure it through the util namespace.
3.5. Automatic assembly
(1) The <bean/> element provides an attribute that specifies the autowire type
3.6. Method Injection
If we inject prototype beans into singleton-mode beans and hope to return a new bean every time we call it, it will not be possible to use traditional injection methods because the action of singleton-mode beans injecting associated beans only occurs once.
(1) An optional solution is to enable the host bean to implement the BeanFactoryAware interface, so that the host bean can access the references of the container, so that the get method can be modified and the container's
factory.getBean("dependated bean") method, you can get the latest bean every time.
(2) The above method couples our code and spring, which is the worst way to do, and we can decouple through method injection.
We only need to define an interface, and define an abstract method to obtain dependent beans in the interface. The spring configuration is as follows:
<beanid="car"class="dependated bean"/><beanid="host"class="interface bean"><lookup-methodname="getCar"bean="car"/></bean>
The lookup-method element tag provides dynamic implementation for getCar() of interface beans. The implementation of method injection mainly relies on the dynamic operation bytecode technology of the Cglib package.
3.7. Method replacement
Use bean2 to replace bean1's getCar method, provided that bean2 must implement the MethodReplacer interface, and the configuration is as follows:
<beanid="bean1"class="aaaaaaaaa"><replaced-methodname="getCar"replacer="bean2"/></bean><beanid="bean2"class="bbbbbbbbbb"/>
4. The relationship between <bean>
4.1. Inheritance
The configuration of the parent bean can be inherited by subclasses to avoid repeated definitions. The configuration is as follows:
<beanid="parent bean"class="aaaaaa"abstract="true"/><beanid="child bean"class="bbbbbb">
Subclasses can override the configuration of the parent class. If the abstract="true" of the parent class is not specified, the parent bean will be instantiated.
4.2. Dependence
Some beans instantiate depend on other beans, and other beans must be instantiated before they can instantiate the host bean. Spring provides the depends-on attribute, and specifies that the dependency bean is instantiated first, such as:
<beanid="host"class="aaaaaa"depends-on="b1"/><beanid="b1"class="bbbbbbbb"/>
If there are multiple pre-dependence beans, you can create the name of the bean by commas, spaces, or semicolons.
4.3. Bean scope
(1) The spring container will instantiate all beans when it is started. If you do not want to instantiate in advance, the lazy-init="true" property of <bean/> can control delayed instantiation, but if the bean is referenced by other beans that need to be instantiated in advance, spring will also ignore the delayed instantiation setting.
(2) Web application-related scope
If the user uses request, session, and globalSession scope, the additional configuration must be done in the web container first:
In lower versions of web containers (before Servlet 2.3), you can use http request filter configuration:
<filter> <filter-name>requestContextFilter</filter-name> <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class> </filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
In higher versions of web containers, you can use the http request listener to configure:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
(3) Scope dependency problem
When injecting web-scoped beans into singleton or prototype beans, use aop, for example:
<bean id="web1" scope="request" > <aop:scoped-proxy/></bean><bean id="singleton1" > <property name="z1" ref="web1" /></bean>
4.4. FactoryBean
Generally speaking, spring uses the class attribute of <bean/> to specify the implementation class instantiation bean through the reflection mechanism. But in some cases, the process of instantiating a bean is more complicated. If in the traditional way, a large amount of configuration information is required in the <bean>. The flexibility of the configuration method is limited, and a simple solution may be obtained by using encoding methods.
Spring provides an org.springframework.beans.factory.FactoryBean factory class interface for this, and users can customize the logic of instantiating beans by implementing this interface.
When the implementation class configured by the class attribute of <bean/> is FactoryBean and its subclass, the return of the FactoryBean() method does not return the FactoryBean and its subclass itself, but the object returned by the FactoryBean getObject() method.
If you want to get the object of FactoryBean and its subclass itself, explicitly prefix the beanName with a "&" prefix, such as getBean("&car5") when the getBean(beanName) method.
5. Annotation-based configuration
5.1. Annotation type
@Component-----Native annotation
Derivative Annotations:
@Repository: Annotate DAO
@Service: label service
@Controller: Annotation controller
5.2. Use annotation configuration information to start the spring container
(1) After spring 2.5, the context namespace was introduced, which provides the application of annotations to define beans by scanning the class package:
<context:component-scan base-package="xxxxxxxxxx" resource-pattern="xxxx/*.class">
Resource-pattern attribute is used to specify classes under specific packages that need to be scanned in the base package
(2) There are more powerful filter sub-labels
<context:component-scan base-package="xxxxxxxxxx" > <context:include-filter type="xxxx" expression="xxxxxxxxxxxxxxxx"/> <context:exclude-filter type="xxxx" expression="xxxxxxxxxxxxxxx"/></context:component-scan>
Of all types, aspectj's filtering ability is the most powerful.
5.3. Automatic assembly of beans
(1) @Autowired
@Autowired matches by type by default. If there is no matching bean in the container, an exception will be thrown when the spring container starts. You can use @Autowired(required=false) for annotation, and no exception will be thrown.
Use @Autowired to directly annotate the method parameters. If a method has multiple parameters, by default, spring automatically selects beans matching the parameter type for injection.
Using @Autowired annotation of collection variables, you can inject all beans that match the element type of the collection, which is very powerful.
Using @Autowired assembler property, there can be no setter method.
(2) @Qualifiler
If there is more than one matching bean in the container, the name of the bean can be qualified by the @Qualifiler annotation.
(3) Support for marking and annotation
spring also supports @Resource defined by JSR-250 and @Inject annotations defined by JSR-330
@Resource requires that a bean's name attribute bean is provided. If the attribute is empty, the variable name or method name will be automatically used as the name of the bean.
(4) Key points:
If you only use @Autowired, we still need to explicitly define the <bean/> node in the xml. The spring container disables annotation assembly by default. The way to enable it is to configure the <context:annotation-config/> element in the xml.
But spring also provides another trick. Using the <context:component-scan/> element, the spring container will automatically detect the bean without explicitly defining the <bean/> node.
spring annotates the annotation class through @Component, @Repository, @Service, and @Controller, so that <context:component-scan/> knows which classes need to be registered as SpringBean.
If you use a third-party jar package and you want to automatically inject classes in the third-party jar package, even if the third-party jar package does not annotate them with annotations, the filter element <context:include-filter> can replace the annotation-based component scanning policy, so that <context:component-scan/> automatically registers classes that meet expression expression expressions.
5.4. Bean's scope of action and life process method
(1) @Scope("xxxx")
The default range of beans configured by annotation is singleton.
spring provides @Scope annotation. When it comes to the class, the annotation parameters are the same as the value of the scope attribute in xml.
(2) Comparison of life process methods
| <bean> | annotation |
| init-method | @PostConstruct |
| Destory-method | @PreDestroy |
Difference: Annotations can define multiple methods in a class, and the methods are executed in order
6. Java-based configuration
6.1. Use java classes to provide Bean definition information
(1) Ordinary POJO can provide bean definition information for spring containers as long as the @Configuration annotation is marked. Each method marked with @Bean is equivalent to providing a bean definition information.
(2) @Bean
The type of a bean is determined by the return value type of the method annotated by @Bean
The default name of the bean is the same as the method name, and it can also be explicitly specified by @Bean (name="xxx").
You can use @Scope at @Bean to indicate the scope of use of the Bean
(3) @Configuration
Since the @Configuration annotation class itself has been marked with @Component annotation, any class marked with @Configurstion can be automatically assembled into other classes using @Autowired.
6.2. Start the spring container using configuration information based on java class
(1) spring provides an AnnotationConfigApplicationContect class, which can directly start the Spring container through the class annotated @Configuration annotation.
(2) When there are multiple configuration classes
You can register one by one through the register method of AnnotationConfigApplicationContect, and then call the refresh method to refresh the container to apply these registered configuration classes.
You can also use @Import (xxx.class) annotation to introduce all other configuration classes into one configuration class, so that you only need to register one configuration class.
(3) Refer to the configuration of @Configuration through the xml configuration class
<context:component-scanbase-package="..."resource-pattern="Configuration Class Name">
(4) Reference XML configuration information in the configuration class
Use @ImportResource("classpath:............") at @Configuration to import the xml configuration file
6.3. Comparison of 3 configuration methods
| XML | annotation | Java Class |
| The implementation class of bean is the current project development | Control the overall logic of bean initialization through code, suitable for scenarios where instantiation of beans is more complex |
Summarize
The above is all the detailed explanation of spring assembling beans in IoC containers. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
A detailed explanation of the three bean configuration methods in Spring 3.x
A brief discussion on the difference between Spring singleton bean and singleton pattern
Detailed explanation of the life cycle of Spring configuration usage
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!