我想将ApplicationContext
本身注入到bean中。
类似
public void setApplicationContext(ApplicationContect context) {
this.context = context;
}
春天有可能吗?
以前的评论都可以,但我通常更喜欢:
@Autowired private ApplicationContext applicationContext;
容易,使用ApplicationContextAware
界面。
public class A implements ApplicationContextAware {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext context) {
this.context = context;
}
}
然后在您实际的applicationContext中,您只需引用您的bean。
<bean id="a" class="com.company.A" />
是,只需实现ApplicationContextAware-接口。
我在上面看到了一些有关@Autowired无法正常工作的评论。以下内容可能会有所帮助。
这将不起作用:
@Route(value = "content", layout = MainView.class)
public class MyLayout extends VerticalLayout implements RouterLayout {
@Autowired private ApplicationContext context;
public MyLayout() {
comps.add(context.getBean(MyComponentA.class)); // context always null :(
}
您必须执行此操作:
@PostConstruct
private void init() {
comps.add(context.getBean(MyComponentA.class)); // context is set :)
}
也请注意,Upload是另一个必须在@PostConstruct范围内设置的组件。这对我来说是一场噩梦。希望这会有所帮助!