由Mybatis发现的一个坑

来源:互联网 发布:牵引变电所接地网优化 编辑:程序博客网 时间:2024/05/17 08:57

源码很重要

Thanks for the report, Osvaldas. This has indeed been an issue known about, at least internally, for some time.

There is a fundamental lifecycle conflict in handling BeanFactoryPostProcessor @Bean methods within @Configuration classes that use @Autowired, @PostConstruct, @Value, etc. Because BFPPs must be instantiated early in the lifecycle, they cause early instantiation of their declaring @Configuration class - too early to recieve the usual post-processing by AutowiredAnnotationBeanPostProcessor and friends.

To resolve this issue, it is now possible to declare @Bean methods as static. This permits the container to detect and invoke these methods without instantiating the @Configuration class, thus avoiding the aforementioned lifecycle issues.

@Bean Javadoc has been updated to reflect, and the commit comment follows:


Author: Chris Beams <cbeams@vmware.com>
Date:   Tue May 10 18:17:26 2011 +0800
 
    Allow static modifier on @Bean methods
    
    Declaring @Bean methods as 'static' is now permitted, whereas previously
    it raised an exception at @Configuration class validation time.
    
    A static @Bean method can be called by the container without requiring
    the instantiation of its declaring @Configuration class. This is
    particularly useful when dealing with BeanFactoryPostProcessor beans,
    as they can interfere with the standard post-processing lifecycle
    necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
    other annotations.
    
    static @Bean methods cannot recieve CGLIB enhancement for scoping and
    AOP concerns. This is acceptable in BFPP cases as they rarely if ever
    need it, and should not in typical cases ever be called by another
    @Bean method.  Once invoked by the container, the resulting bean will
    be cached as usual, but multiple invocations of the static @Bean method
    will result in creation of multiple instances of the bean.
    
    static @Bean methods may not, for obvious reasons, refer to normal
    instance @Bean methods, but again this is not likely a concern for BFPP
    types. In the rare case that they do need a bean reference, parameter
    injection into the static @Bean method is technically an option, but
    should be avoided as it will potentially cause premature instantiation
    of more beans that the user may have intended.
    
    Note particularly that a WARN-level log message is now issued for any
    non-static @Bean method with a return type assignable to BFPP.  This
    serves as a strong recommendation to users that they always mark BFPP
    @Bean methods as static.
    
    See @Bean Javadoc for complete details.
    
    Issue: SPR-8257, SPR-8269