Spring Boot creates beans using Java code and registers them to Spring.

Source: Internet
Author: User

Spring Boot creates beans using Java code and registers them to Spring.

From Spring3.0, a new method is added to configure Bean Definition, which is to configure Bean Definition through Java Code.
The two configuration methods differ from Xml and Annotation:

The first two Xml and Annotation configuration methods are pre-defined, that is, after developers use the XML file or Annotation to pre-configure bean attributes, start the Spring container, the Spring container will first parse these configuration attributes to generate corresponding? Bean Definition, which is loaded into the ultlistablebeanfactory object attribute container. At the same time, the Spring framework also defines some internal Bean definitions, such as the ConfigurationClassPostProcessor definition of the bean name "org. springframework. context. annotation. internalConfigurationAnnotationProcessor.

At this moment, no Bean Definition parsing action will be performed. The Spring framework filters out BeanDefinitionRegistryPostProcessor-type Bean definitions based on the first two configurations, and generate the corresponding Bean object (such as the ConfigurationClassPostProcessor instance) through the Spring framework ). According to the Spring context source code, this object is a tool class of the processor type. The Spring container will call the postProcessBeanDefinitionRegistry (…) of the processor before instantiating the Bean defined by the developer (...) Method. In this example, Bean Definition is configured based on Java Code.

Bean parsing Sequence Diagram Based on Java Code

This figure is for your understanding. I will not describe it in detail here.

Java Code-based configuration method, the execution principle is different from the first two. After the Spring framework has Parsed the configuration based on XML and Annotation, it adds BeanDefinitionRegistryPostProcessZ? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> release + io6zIw7 + qt6LIy9Sxzai5/release/T0Lj8uN + 1 xMHpu + release + L + release/release + sgSmF2YSC0 + signature/Signature + oaM8L3A + signature/Signature + DQoJy/Signature + 0tL2o1q7HsMb0tq + signature/Signature + signature + DQoJPHA + signature/Signature + signature/WphdmG0 + sLrtLS9qGJlYW6jrLKi16Ky4c6qU3ByaW5nudzA7aGjPGJyIC8 + combined/atcQyuPbKtc/WwOCjrLfWsfDD/MP7srvNrLXEw/Rewrite "brush: java; ">package org.springboot.sample.config;public interface Shanhy {void display();}

2. Implementation class ShanhyA. java

package org.springboot.sample.config;public class ShanhyA implements Shanhy {@Overridepublic void display() {System.out.println("AAAAAAAAAAAA");}}

3. Implementation class ShanhyB. java

package org.springboot.sample.config;public class ShanhyB implements Shanhy {@Overridepublic void display() {System.out.println("BBBBBBBBBBBB");}}

4. Implementation of BeanDefinitionRegistryPostProcessor

Package org. springboot. sample. config; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. beans. beansException; import org. springframework. beans. factory. annotation. annotatedGenericBeanDefinition; import org. springframework. beans. factory. config. beanDefinitionHolder; import org. springframework. beans. factory. config. configurableListableBeanFactory; import org. springframework. be Ans. factory. support. beanDefinitionReaderUtils; import org. springframework. beans. factory. support. beanDefinitionRegistry; import org. springframework. beans. factory. support. beanDefinitionRegistryPostProcessor; import org. springframework. beans. factory. support. beanNameGenerator; import org. springframework. context. annotation. annotationBeanNameGenerator; import org. springframework. context. annotation. annotation ConfigUtils; import org. springframework. context. annotation. annotationScopeMetadataResolver; import org. springframework. context. annotation. configuration; import org. springframework. context. annotation. scopeMetadata; import org. springframework. context. annotation. scopeMetadataResolver;/*** implement self-instantiated bean and register it as Spring management ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/* @ create January 21, 2016 */@ Configur Ationpublic class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {private static final Logger logger = LoggerFactory. getLogger (MyBeanDefinitionRegistryPostProcessor. class); private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver (); private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator (); @ Overridepublic vo Id response (describeanfactory) throws BeansException {logger.info ("Invoke Metho injection") ;}@ Overridepublic void response (registry) throws BeansException {logger.info ("Invoke Metho injection "); registerBean (registry, "shanhyA", ShanhyA. class); registerBean (registry, "shanhyB", ShanhyB. class);} private void registerBean (BeanDefinitionRegistry, String name, Class beanClass) {incluabd = new AnnotatedGenericBeanDefinition (beanClass); ScopeMetadata scopeMetadata = this. scopeMetadataResolver. resolveScopeMetadata (abd); abd. setScope (scopeMetadata. getScopeName (); // You can automatically generate nameString beanName = (name! = Null? Name: this. beanNameGenerator. generateBeanName (abd, registry); AnnotationConfigUtils. processCommonDefinitionAnnotations (abd); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder (abd, beanName); BeanDefinitionReaderUtils. registerBeanDefinition (definitionHolder, registry );}}

5. Test
We can directly inject our objects as usual. For the same interface, we need to specify the name

/*** Test parameter injection ** @ author single Hongyu (365384722) * @ myblog repository @ create January 13, 2016 */@ Configurationpublic class MyConfiguration {@ Beanpublic FilterRegistrationBean repository (@ Qualifier ("shanhyB") Shanhy shanhy) {filterRegistrationBean filterRegistration = new handler (); shanhy. display (); // omitting the code return filterRegistration ;}}

Use @ Resource or @ Autowired and specify @ Qualifier.

@ RestController @ RequestMapping ("/hello") public class HelloController {@ Resource (name = "shanhyA") private Shanhy shanhyA; @ Autowired @ Qualifier ("shanhyB") private Shanhy shanhyB; // omitting code}

Here is a bit of experience. In @ Configuration, injection of injection properties cannot be used, but only parameters can be used. The reason is that the @ Configuration class is loaded at the beginning, in this case, if you want to inject attributes, the bean objects to be injected do not exist yet.

In the next article, we will use this method to dynamically create multiple data sources based on MyBatis.

Related Article

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.