68

我想将一个ApplicationContext自身注入一个bean。

就像是

public void setApplicationContext(ApplicationContect context) {
  this.context = context;
}

春天可以吗?

4

5 回答 5

132

以前的评论还可以,但我通常更喜欢:

@Autowired private ApplicationContext applicationContext;
于 2011-02-07T01:33:49.897 回答
44

很简单,使用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" />
于 2011-02-06T14:57:36.203 回答
13

是的,只需实现ApplicationContextAware -interface。

于 2011-02-06T14:58:09.033 回答
3

我在上面看到了一些关于 @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();
  }
}
于 2020-05-08T16:52:34.437 回答
2

特殊解决方案:从任何(非 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);
    }
}
于 2021-02-25T09:32:19.523 回答