我可以将ApplicationContext定义为Spring XML配置中的构造函数arg吗?

Rob*_*her 5 spring

如果我需要访问ApplicationContext我的bean类的构造函数,有没有办法可以用XML配置bean而不是实现ApplicationContextAware

注意:我知道我可以使用注释驱动的配置并使用标记构造函数来完成此操作@Autowire.我特别感兴趣的是XML配置是否可行.

xer*_*593 1

需要

访问我的 bean 类的构造函数中的 ApplicationContext

已经是“坏”了...:[1] [2](请主要尝试摆脱这种需求/改变主意!:)

当然,ref="applicationContext"会很好,但它不起作用/没有人知道如何,...但是这种“大锤”方法可以克服:[3](2007...mmmhk,...“轮子”甚至更老....;)

..一个“单应用程序上下文包装器 bean”,您可以(构造函数)在任何地方注入(几乎;)。(如在 xml 中,如在 java 配置中。)

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

applicationContext.xml:

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

<bean id="myCtxtDependentBean" class="[some.package.]CrazyBean" >
   <constructor-arg ref="myWrapper" />
</bean>
Run Code Online (Sandbox Code Playgroud)

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...
    }
}
Run Code Online (Sandbox Code Playgroud)