How to inject ApplicationContext itself

Solution 1:

Previous comments are ok, but I usually prefer:

@Autowired private ApplicationContext applicationContext;

Solution 2:

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" />

Solution 3:

Yes, just implement the ApplicationContextAware -interface.

Solution 4:

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();
  }
}

Solution 5:

Special solution: get Spring beans from any (non Spring) classes

@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);
    }
}