How to inject ApplicationContext itself

前端 未结 4 1907
旧时难觅i
旧时难觅i 2020-11-30 02:11

I want to inject an ApplicationContext itself to a bean.

Something like

public void setApplicationContext(ApplicationContect context) {
         


        
相关标签:
4条回答
  • 2020-11-30 02:46

    Yes, just implement the ApplicationContextAware -interface.

    0 讨论(0)
  • 2020-11-30 02:46

    I saw some comments above about @Autowired not working still. The following may help.

    This will not work:

    @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 :(
    }
    

    You must do this:

     @Autowired
      public MyLayout(ApplicationContext context) {
        comps.add(context.getBean(MyComponentA.class)); //context is set :)
    }
    
    

    or this:

    
    @PostConstruct
        private void init() {
        comps.add(context.getBean(MyComponentA.class)); // context is set :)
    }
    

    Also note that Upload is another component that must be set within the scope of @PostConstruct. This was a nightmare for me to figure out. Hope this helps!

    I almost forgot to mention that the @Scope annotation may be necessary for your Bean, as seen below. This was the case when using Upload within a Bean because the UI is not instantiate/attached prior to the Bean being created and will cause a Null Reference Exception to be thrown. It won't do so when using @Route, but will when using @Component - so the latter is not an option and if @Route is not viable, then I would recommend using @Configuration class to create the bean with the prototype scope.

    @Configuration
    public class MyConfig {
      @Bean
      @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
      public MyComponentA getMyBean() {
        return new MyComponentA();
      }
    }
    
    0 讨论(0)
  • 2020-11-30 02:52

    Previous comments are ok, but I usually prefer:

    @Autowired private ApplicationContext applicationContext;
    
    0 讨论(0)
  • 2020-11-30 02:52

    Easy, using the ApplicationContextAware interface.

    public class A implements ApplicationContextAware {
      private ApplicationContext context;
    
      public void setApplicationContext(ApplicationContext context) {
          this.context = context;
      }
    }
    

    Then in your actual applicationContext you only need to reference your bean.

    <bean id="a" class="com.company.A" />
    
    0 讨论(0)
提交回复
热议问题