我想将一个ApplicationContext
自身注入一个bean。
就像是
public void setApplicationContext(ApplicationContect context) {
this.context = context;
}
春天可以吗?
我想将一个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 -interface。
我在上面看到了一些关于 @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 :(
}
你必须这样做:
@Autowired
public MyLayout(ApplicationContext context) {
comps.add(context.getBean(MyComponentA.class)); //context is set :)
}
或这个:
@PostConstruct
private void init() {
comps.add(context.getBean(MyComponentA.class)); // context is set :)
}
另请注意,Upload 是另一个必须在@PostConstruct 范围内设置的组件。这对我来说是一场噩梦。希望这可以帮助!
我几乎忘了提到 @Scope 注释可能对您的 Bean 是必需的,如下所示。在 Bean 中使用 Upload 时就是这种情况,因为 UI 在创建 Bean 之前没有实例化/附加,并且会导致抛出空引用异常。使用@Route 时不会这样做,但使用@Component 时会这样做 - 所以后者不是一个选项,如果@Route 不可行,那么我建议使用@Configuration 类来创建具有原型范围的bean。
@Configuration
public class MyConfig {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyComponentA getMyBean() {
return new MyComponentA();
}
}
特殊解决方案:从任何(非 Spring)类中获取 Spring bean
@Component
public class SpringContext {
private static ApplicationContext applicationContext;
@Autowired
private void setApplicationContext(ApplicationContext ctx) {
applicationContext = ctx;
}
public static <T> T getBean(Class<T> componentClass) {
return applicationContext.getBean(componentClass);
}
}