我正在使用带有SpringBoot的Spring 4和带有Java配置的Spring-Web.
要让@PostConstructSpring在启动时执行带注释的方法,必须注册CommonAnnotationBeanPostProcessor上下文,否则将@PostConstruct被忽略.
在基于XML的Spring配置中,文档说要使用(在beans元素下)
<context:annotation-config/>
Run Code Online (Sandbox Code Playgroud)
我还看到了一个示例,其中注册是在单个bean的基础上完成的,如下所示:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
Run Code Online (Sandbox Code Playgroud)
如果可能,我希望避免这种情况.我的项目不包含任何XML文件,并且在我的构建文件夹中没有为我生成任何文件.
目前,我的解决方案是用我的类来注释@ComponentScan,我认为这会导致Spring检测并注册@Components和@Beans.不知何故,这导致CommonAnnotationBeanPostProcessor被调用,虽然我不知道为什么,但它解决了我的问题!
(这个类有一个@Autowired属性,在启动时为null - 因此需要进行初始化@PostConstruct)
但同样,我的问题是,使用Java配置实现这一目标的正确方法是什么?谢谢!