Spring Container Post Processor beanfactorypostprocessor Use a problem to be aware of

Source: Internet
Author: User


Beanfactorypostprocessor and Beanpostprocessor



The former is for the container, that is, when the container starts, all the beanfactorypostprocessor are executed once,



When you customize Beanfactorypostprocessor yourself, and in the form of javaconfig, for example


package com.fengdui.dubbo.config;

import com.alibaba.dubbo.config. *;
import com.alibaba.dubbo.config.spring.AnnotationBean;
import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.fengdui.dubbo.service.IDubboDemoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/ **
 * @author FD
 * @date 2016/12/20
 * /
@Configuration
// @ PropertySource (value = "classpath: /dubbo.properties")
public class DubboConfig {

    @Value ("$ {dubbo.application.name}")
    private String applicationName;

// @Value ("$ {dubbo.application.logger}")
// private String logger;

    @Value ("$ {dubbo.registr.protocol}")
    private String protocol;

    @Value ("$ {dubbo.registry.address}")
    private String registryAddress;

    @Value ("$ {dubbo.protocol.name}")
    private String protocolName;

    @Value ("$ {dubbo.protocol.port}")
    private int protocolPort;

    @Value ("$ {dubbo.provider.timeout}")
    private int timeout;

    @Value ("$ {dubbo.provider.retries}")
    private int retries;

    @Value ("$ {dubbo.provider.delay}")
    private int delay;

    @Value ("$ {dubbo.annotation.package}")
    private String packageName;


// @Bean
// public ReferenceBean referenceBean (ApplicationConfig application, RegistryConfig registry) {
// // reference the remote service
// ReferenceBean <IDubboDemoService> reference = new ReferenceBean <IDubboDemoService> (); // This instance is very heavy and encapsulates the connection with the registry and the connection with the provider. Please cache it yourself, otherwise memory and connection leaks may occur
// reference.setApplication (application);
// reference.setRegistry (registry); // multiple registries can use setRegistries ()
// reference.setInterface (IDubboDemoService.class);
// reference.setVersion ("1.0.0");
// // use xxxService like local beans
//// IDubboDemoService xxxService = reference.get (); // Note: This proxy object encapsulates all communication details internally, the object is heavy, please cache reuse
// return reference;
//}


    / **
     * Inject dubbo context
     * @return
     * /
    @Bean
    public ApplicationConfig applicationConfig () {
        System.out.println (delay);
        // current application configuration
        ApplicationConfig applicationConfig = new ApplicationConfig ();
        applicationConfig.setName (this.applicationName);
        return applicationConfig;
    }

    @Bean
    public AnnotationBean annotationBean (/ * @ Value ("$ {dubbo.annotation.package}") String packageName * /) {

        System.out.println ("Fd");
        AnnotationBean annotationBean = new AnnotationBean ();
        annotationBean.setPackage (packageName);
        return annotationBean;
    }

    / **
     * Inject the dubbo registry configuration, based on zookeeper
     *
     * @return
     * /
    @Bean
    public RegistryConfig registryConfig () {
        // Connect the registry configuration
        RegistryConfig registry = new RegistryConfig ();
        registry.setProtocol (protocol);
        registry.setAddress (registryAddress);
        return registry;
    }

    / **
     * Provide services based on dubbo protocol by default
     *
     * @return
     * /
    @Bean
    public ProtocolConfig protocolConfig () {
        // service provider protocol configuration
        ProtocolConfig protocolConfig = new ProtocolConfig ();
        protocolConfig.setName (protocolName);
        protocolConfig.setPort (protocolPort);
        protocolConfig.setThreads (200);
        System.out.println ("default protocolConfig:" + protocolConfig.hashCode ());
        return protocolConfig;
    }

    / **
     * dubbo service provided
     *
     * @param applicationConfig
     * @param registryConfig
     * @param protocolConfig
     * @return
     * /
    @Bean (name = "defaultProvider")
    public ProviderConfig providerConfig (ApplicationConfig applicationConfig, RegistryConfig registryConfig, ProtocolConfig protocolConfig) {
        System.out.println (delay);
        ProviderConfig providerConfig = new ProviderConfig ();
        providerConfig.setTimeout (timeout);
        providerConfig.setRetries (retries);
        providerConfig.setDelay (delay);
        providerConfig.setApplication (applicationConfig);
        providerConfig.setRegistry (registryConfig);
        providerConfig.setProtocol (protocolConfig);
        return providerConfig;
    }
} 

First of all, Annotationbean implements the Beanfactorypostprocessor interface,





If you follow the above, you will find that the @value annotation is not in effect,



Need to add static before the method





    @Bean public
    static Annotationbean Annotationbean (@Value ("${dubbo.annotation.package}") String PackageName) {

        Annotationbean Annotationbean = new Annotationbean ();
        Annotationbean.setpackage (PackageName);
        return annotationbean;
    }

If it is not static, then the bean will be dependent on the external bean, that is, Getbean ("Annotationbean") will also Getbean ("Dubboconfig")





Trigger Getbean ("Annotationbean"), is the Invokebeanfactorypostprocessors method in the Abstractapplicationcontext when the container is started,



At this time Beanpostprocessor has not been registered, that is, Hasinstantiationawarebeanpostprocessors is false,



When you getbean, you use the Populatebean method to inject the attribute, where the logic for the injection of the value annotation





if (Hasinstawarebpps | | needsdepcheck) {
    propertydescriptor[] Filteredpds = Filterpropertydescriptorsfordependencycheck (BW, mbd.allowcaching);
    if (Hasinstawarebpps) {for
        (Beanpostprocessor bp:getbeanpostprocessors ()) {
            if (BP instanceof Instantiationawarebeanpostprocessor) {
                Instantiationawarebeanpostprocessor IBP = ( Instantiationawarebeanpostprocessor) BP;
                PVs = Ibp.postprocesspropertyvalues (PVs, Filteredpds, Bw.getwrappedinstance (), beanname);
                if (PVs = = null) {
                    return;}}}
    }
    if (Needsdepcheck) {
        checkdependencies (beanname, MBD, Filteredpds, PVS);
    }
}

Hasinstawarebpps here is false, there is no attribute injection (the attribute injection will use a autowiredannotationbeanpostprocessor), so the above @value does not take effect,








Documentation is also described



Http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Bean.html






beanfactorypostprocessor-returning @Bean Methods






Special consideration must is taken for @Bean methods, return Springbeanfactorypostprocessor (BFPP) types. Because BFPP objects must be instantiated very early in Thecontainer lifecycle, they can interfere with processing of anno Tations such as@autowired, @Value, and @PostConstruct within@configuration classes. To avoid theselifecycle issues, Mark Bfpp-returning@bean methods as static. For example:


     @Bean public
     Static Propertyplaceholderconfigurer PPC () {
         //instantiate, configure and return PPC ...
     }
By marking this method as static, it can be invoked without causing instantiation of itsdeclaring @Configuration class, Th US avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods is not being enhanced for scoping and aopsemantics as mentioned above. This works out in BFPP cases, as they is typicallyreferenced by and other @Bean methods. As a reminder, a warn-level log message would beissued for any non-static @Bean methods have a return type assignable to Beanfactorypostprocessor.








The custom beanfactorypostprocessor is configured in Javaconfig mode to add static.



2018.03.14 Update--------------------------------------------------------------------------------------






In the Configurationclassbeandefinitionreader#loadbeandefinitionsforbeanmethod method



if (Metadata.isstatic ()) {//static @Bean method
Beandef.setbeanclassname (Configclass.getmetadata (). GetClassName ());
Beandef.setfactorymethodname (MethodName);
}
else {
Instance @Bean method
Beandef.setfactorybeanname (Configclass.getbeanname ());
Beandef.setuniquefactorymethodname (MethodName);
}



If it's non-static, it will set a Factorybean, which in my case is Dubboconfig



Then the container starts to get this annotationbean, and when it finds Factorybeanname, it will Getbean again ("Dubboconfig"),



But the beanpostprocess that handles @value annotations is not ready yet.



Abstractautowirecapablebeanfactory#instantiateusingfactorymethod = "



Constructorresolver#instantiateusingfactorymethod


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.