java - "this"Spring XML 中 applicationcontext 的引用

标签 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>

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

最佳答案

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

Invoked after population of normal bean properties but before an init callback such as InitializingBean.afterPropertiesSet() or a custom init-method. Invoked after ResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader), ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) and MessageSourceAware, if applicable.

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

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

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

public class SomeClass {
    //your class definition
    @Autowired
    private ApplicationContext myContext;
}

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

关于java - "this"Spring XML 中 applicationcontext 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7892667/

相关文章:

java - 当接口(interface)的方法没有任何实现而我们每次都必须重写它们时,使用接口(interface)的目的是什么?

java - 使用 Java 获取存档中文件的文件或 URI 对象?

Java - 在滚动文本中插入换行符

java - 如何从数据库中获取用户名和密码并传递给 Spring MVC 中的方法

java - 将 SQL 查询放入 CrudRepository 中以限制列(以及此后的进一步 SQL 查询)

java - 如何在 java 中使用 Windows 凭据自动登录?

java - 当从同一类中的另一个安全方法调用安全方法时,@PreAuthorize 不起作用

java - 通过代码更改样式主题中的文本颜色

java - 为什么我的常规应用程序上下文无法加载我的属性文件?

spring - 添加了 Springfox Swagger-UI 但它不起作用,我错过了什么?