background
In Spring, we always unscrupulously obtain Bean objects through IOC. In line with the principle of thinking of the source after drinking water, we will analyze in detail the various gestures injected by Bean. In fact, there is another key point. I like to ask this question during the interview. What do you know about Spring Bean injection? Instead of Spring's Bean acquisition method.
1. XML injection
XML injection is the most native injection method. An XML configuration file and a Bean configuration object can inject a Bean into the Spring container.
<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.xsd"> <!--Generated by reflection mechanism id And name Field assignment calls set And get method--> <bean id="xmlUser" class="com.yiang.code.bean.entity.User"> <property name="id" value="10"/> <property name="name" value="yiang"/> </bean> </beans>
The above code represents injecting an object with id name user into the spring container. Get through ApplicationContext getBean("user", User.class); Just get it.
2. @Bean injection
@ configuration + @Bean annotation is equivalent to the simplified annotation form of XML injection method. Add @ configuration annotation to a configuration class, and use @ Bean annotation to inject object interface in the class. ID is method name
@Configuration public class SpringTestConfig { @Bean public User user() { return new User(2, "yiang"); } }
The above code means to inject a user entity with ID 2 and name Yang into the Spring container. For other descriptions of Bean annotations, please refer to this article: Peeping into Bean loading in Spring.
3. @Conditional condition judgment
The Condition injection annotation of @ Bean is used together with @ Bean during object injection. You can specify the Condition processing class through @ Conditional(WindowsCondition.class). The processing class makes relevant logical judgment by implementing the Condition interface. The following code indicates that the Bean can be injected into the Spring container only if the operating system is Windows10.
public class WindowsCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String property = environment.getProperty("os.name"); return "Windows 10".equals(property); } }
4. @Import import
@ Import import Import annotation, which is used in the class header and contains a class <? > The array parameter of [] can be passed into multiple classes. Generally, it is more used for external jar object Import. The imported object ID is its full path name. The difference from @ Bean annotation is that @ Bean Import defaults to method name or lowercase hump. The usage is as follows
@Import({PayEntity.class}) public class SpringTestConfig {
Represents the PayEntity class object of injection configuration. The injected ID is as follows:
com.yiang.code.entity.PayEntity
5. @EnableXXX support Import
@ EnableXXX is the guide package implementation of most frameworks. The prominent chestnuts are @ EnableEureka (Registry), @ EnableFeignClients (Feign client), @ EnableAsync (asynchronous annotation).
We can see that the @ EnableAsync asynchronous annotation source code is actually processed through the @ Import annotation called. In other words, the @ enablexxx annotation is actually an encapsulation of the @ Import annotation. When configuring Import, you only need to use a @ enablexxx without specifying a class to Import. Simpler and cleaner.
6. Import selector interface
The ImportSelector interface is implemented through the handwriting class and injected into the Spring container to realize custom object injection. In fact, in the previous @ EnableAsync, the pointed AsyncConfigurationSelector class uses this method to guide the package by implementing ImportSelector (base class) and then implementing selectImports method, To return the corresponding class name and inject it into the Spring container.
7. ImportBeanDefinitionRegistrar interface} custom Bean registrar
The ImportBeanDefinitionRegistrar interface is implemented through the handwriting class and injected into the Spring container. There is no difference between the injection form and the @ ImportSelector interface. You can implement the interface method. The following code represents the injection of RegisterEntity
Class into the container with ID registerEntity.
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(RegisterEntity.class); registry.registerBeanDefinition("registerEntity", rootBeanDefinition); } }
8. FactoryBean interface instance registration factory
Note the difference between FactoryBean interface and BeanFactory. This interface registers Bean objects, while BeanFactory interface obtains Bean objects.
The implementation method is also relatively simple. The isSingleton method determines whether a singleton is implemented. By default, it will not be enforced. It is false. Changing the implementation to true is the singleton mode. Others are to return the corresponding object and class instances.
public class MyFactoryBean implements FactoryBean<MyFactoryBeanEntity> { public MyFactoryBeanEntity getObject() { return new MyFactoryBeanEntity(); } public Class<?> getObjectType() { return MyFactoryBeanEntity.class; } public boolean isSingleton() { return true; } }
During injection, you can register this class with @ Bean or Import it with @ Import
@Bean public MyFactoryBean myFactoryBean() { return new MyFactoryBean(); }
9. Annotation of @ component component @ Service, @ Repository, @ Controller
In the normal project development architecture, these annotations are used most@ Repository represents the Dao layer of Mapper file, @ Service represents the business logic layer, and @ Controller represents the control layer. It should be noted that @ RestController is not an annotation of Spring package. Therefore, it is not explained here. In fact, the core of the three annotations for code grouping is the dependent @ Component annotation. Just make a distinction. In fact, there is no gap inside.
summary
The above are the nine Bean injection methods in Spring. Many of them are basically the same and can be used flexibly according to needs. We can also choose the way we like in the actual project to ensure its applicability and rationality.