我有一个用例,我需要在ApplicationContext加载时只在bean中调用一个(非静态)方法.如果我使用MethodInvokingFactoryBean吗?或者我们有更好的解决方案?
作为旁注,我使用ConfigContextLoaderListener在Web应用程序中加载应用程序上下文.并希望,如果bean'A'被实例化,只需调用methodA()一次.
怎么能很好地做到这一点?
我想在 MyComponent 类中使用 ApplicationContext 实例。当我尝试自动装配时,Spring 在启动时初始化我的组件时出现空指针异常。
有没有办法在 MyComponent 类中自动装配 ApplicationContext ?
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
@Autowired
MyComponent myComponent;
@Autowired
ApplicationContext context; //Spring autowires perfectly at this level
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
@Component
public class MyComponent{
@Autowired
ApplicationContext ctx;
public MyComponent(){
ctx.getBean(...) //throws null pointer
}
}
Run Code Online (Sandbox Code Playgroud)