将预构造的Bean添加到Spring应用程序上下文中 [英] Adding a Pre-constructed Bean to a Spring Application Context

查看:133
本文介绍了将预构造的Bean添加到Spring应用程序上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个实现以下方法的类:

I am writing a class that implements the following method:

public void run(javax.sql.DataSource dataSource);

在此方法中,我希望使用类似于以下内容的配置文件构造Spring应用程序上下文:

Within this method, I wish to construct a Spring application context using a configuration file similar to the following:

<bean id="dataSource" abstract="true" />

<bean id="dao" class="my.Dao">
  <property name="dataSource" ref="dataSource" />
</bean>

是否有可能强制Spring使用传递给我的方法的DataSource对象,无论dataSourcebean在哪里在配置文件中引用?

Is it possible to force Spring to use the DataSource object passed to my method wherever the "dataSource" bean is referenced in the configuration file?

推荐答案

我发现可以使用两个Spring接口来实现我需要的东西。 BeanNameAware 界面允许Spring通过调用 setBeanName(String)方法。 FactoryBean 界面告诉Spring不要使用对象本身,而是在 getObject()方法。将它们组合在一起就得到:

I discovered two Spring interfaces can be used to implement what I need. The BeanNameAware interface allows Spring to tell an object its name within an application context by calling the setBeanName(String) method. The FactoryBean interface tells Spring to not use the object itself, but rather the object returned when the getObject() method is invoked. Put them together and you get:

public class PlaceholderBean implements BeanNameAware, FactoryBean {

    public static Map<String, Object> beansByName = new HashMap<String, Object>();

    private String beanName;

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    @Override
    public Object getObject() {
        return beansByName.get(beanName);
    }

    @Override
    public Class<?> getObjectType() {
        return beansByName.get(beanName).getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}

bean定义现在缩减为:

The bean definition is now reduced to:

<bean id="dataSource" class="PlaceholderBean" />

占位符在创建应用程序上下文之前会收到其值。

The placeholder receives its value before creating the application context.

public void run(DataSource externalDataSource) {
    PlaceholderBean.beansByName.put("dataSource", externalDataSource);
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    assert externalDataSource == context.getBean("dataSource");
}

事情似乎成功运作!

这篇关于将预构造的Bean添加到Spring应用程序上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆