在spring中,如果bean实现了ApplicationContextAware,那么它就可以访问了applicationContext.因此它能够获得其他豆类.例如
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
Run Code Online (Sandbox Code Playgroud)
然后SpringContextUtil.getApplicationContext.getBean("name")可以获得bean"名称".
要做到这一点,我们应该把它SpringContextUtil放在applications.xml例如
<bean class="com.util.SpringContextUtil" />
Run Code Online (Sandbox Code Playgroud)
这里的bean SpringContextUtil不包含属性applicationContext.我想当spring bean初始化时,会设置此属性.但这是怎么做到的?如何setApplicationContext调用该方法?
为了提供一些运行时生成的API文档,我想迭代所有Spring MVC控制器.所有控制器都使用Spring @Controller注释进行注释.目前我这样做:
for (final Object bean: this.context.getBeansWithAnnotation(
Controller.class).values())
{
...Generate controller documentation for the bean...
}
Run Code Online (Sandbox Code Playgroud)
但是这个代码的第一个电话是EXTREMELY缓慢.我想知道Spring是否迭代了类路径中的所有类,而不仅仅是检查已定义的bean.在运行上述代码时,控制器已经加载,日志显示所有这些控制器的请求映射,因此Spring MVC必须已经全部知道它们,并且必须有更快的方法来获取它们的列表.但是怎么样?
我正在使用Spring Boot 1.3.3和JavaFX.应用程序成功启动Splash屏幕(此时applicationContext不为null)
@SpringBootApplication
public class PirconApplication extends Application{
@Bean(name = "primaryStage")
public Stage getPrimaryStage() {
return new Stage(StageStyle.DECORATED);
}
private ConfigurableApplicationContext applicationContext = null;
private static String[] args = null;
@Override
public void stop() throws Exception {
super.stop();
Platform.exit();
applicationContext.close();
}
@Override
public void start(Stage primaryStage) throws Exception {
Task<Object> worker = worker();
worker.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
try {
AppSplashController loader = applicationContext.getBean(AppSplashController.class);
Stage stage = applicationContext.getBean(Stage.class);
stage.setScene(loader.init());
stage.initStyle(StageStyle.UNDECORATED);
stage.show();
} catch (IOException e) …Run Code Online (Sandbox Code Playgroud) 我想在 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)