Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define ApplicationContext as a constructor-arg in Spring XML configuration?

Tags:

spring

If I need access to the ApplicationContext in the constructor of my bean class is there a way I can configure the bean in XML rather than implementing ApplicationContextAware?

Note: I know I can do this using annotation-driven configuration and marking the constructor with @Autowire. I'm specifically interested in whether it's possible with XML configuration.

like image 324
Rob Fletcher Avatar asked Feb 03 '15 06:02

Rob Fletcher


1 Answers

The need to

access to the ApplicationContext in the constructor of my bean class

is already "bad"...: [1] [2] (please primarily try to get rid of this need/change your mind!:)

Of course, ref="applicationContext" would be nice, but it doesn't work/noone knows how, ...but this "sledgehammer" approach can overcome: [3] (2007...mmmhk, ..."the wheel" is even older....;)

..a "singelton application context wrapper bean", which you can (constructor-) inject (almost;) everywhere. (As in xml, as in java config.)

ApplicationContextWrapper.java:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
*  Thx to: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
**/
public class ApplicationContextWrapper implements ApplicationContextAware {
  /** the original post has static variable and get-method, but within spring context,
  * and clean initialisation&wiring, it can be oblet.**/
  private /*static*/ ApplicationContext CONTEXT;

  @Override
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  public /*static*/ ApplicationContext getContext() {
    return CONTEXT;
  }
}

applicationContext.xml:

<bean id="myWrapper" class="[some.package.]ApplicationContextWrapper"/>

<bean id="myCtxtDependentBean" class="[some.package.]CrazyBean" >
   <constructor-arg ref="myWrapper" />
</bean>

CrazyBean.java:

public class CrazyBean {

    public CrazyBean(ApplicationContextWrapper wrapper) {
        ApplicationContext ctxt = wrapper.getContext();
        // do crazy stuff here :)
    }

    // or in a static variant, just:
    public CrazyBean() { // ...no arguments, no injection
       ApplicationContext ctxt = ApplicationContextWrapper.getContext();
       // but ensure setApplicationContext's been called...
    }
}
like image 196
xerx593 Avatar answered Sep 28 '22 13:09

xerx593