Spring XML 中 applicationContext 的“this”引用

jav*_*y79 5 java spring

有什么方法可以在 Spring 的 bean 配置文件中引用当前应用程序上下文吗?

我正在尝试做这样的事情:

<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <bean id="some-bean-name" class="com.company.SomeClass">
        <constructor-arg>
            <!-- obviously this isn't right -->
            <bean ref=#{this}/>
        </constructor-arg>
    </bean>
Run Code Online (Sandbox Code Playgroud)

问题是SomeClass它的构造函数中需要一个 ApplicationContext 实例。有什么方法可以获取正在加载 bean 的 ApplicationContext 的引用吗?我知道我可以在 XML 中完成所有加载,但这并不是我想要的,因为我需要在 java 代码中加载 bean。

nic*_*ild 1

您考虑过实施ApplicationContextAware吗?它不会出现在构造函数中,但会在调用之前发生init(),并且会在填充 bean 属性之后发生。

在填充普通 bean 属性之后但在初始化回调(例如 InitializingBean.afterPropertiesSet() 或自定义初始化方法)之前调用。在 ResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader)、ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) 和 MessageSourceAware(如果适用)之后调用。

public class SomeClass implements ApplicationContextAware {
    //your class definition
    private ApplicationContext myContext;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        myContext = context;
        //load beans here maybe?
    }
}
Run Code Online (Sandbox Code Playgroud)

@Autowire(d)如果使用 Spring 2.5 或更高版本,您也可以只使用它。

public class SomeClass {
    //your class definition
    @Autowired
    private ApplicationContext myContext;
}
Run Code Online (Sandbox Code Playgroud)

当然,执行其中任何一个都会将您的代码与 Spring 绑定。