Adding a Pre-constructed Bean to a Spring Application Context

后端 未结 6 1913
醉话见心
醉话见心 2020-12-24 02:24

I am writing a class that implements the following method:

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

Within this method, I wish to

6条回答
  •  既然无缘
    2020-12-24 03:17

    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 beansByName = new HashMap();
    
        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;
        }
    
    }
    

    The bean definition is now reduced to:

    
    

    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");
    }
    

    Things appear to be working successfully!

提交回复
热议问题