深入spring ——加载外部配置bean到当前容器中
最近在阅读spring源码,(看,,,心累),对于结果,当然是希望对实际开发有所用。所以,在这过程中打算做点笔记。在spring已经启动的情况下,希望从配置文件中再加入bean和bean所需要的参数,比如从把各种bean.xml文件保存在数据库中xml文件中有类的一些属性,需要时再加载所需的配置该类,并且set属性到当前容器中。具体看以下例子把。首先,创建已经MyBean类(因为map属性
·
最近在阅读spring源码,(看,,,心累),对于结果,当然是希望对实际开发有所用。所以,在这过程中打算做点笔记。
在spring已经启动的情况下,希望从配置文件中再加入bean和bean所需要的参数,比如从把各种bean.xml文件保存在数据库中xml文件中有类的一些属性,需要时再加载所需的配置该类,并且set属性到当前容器中。具体看以下例子把。
首先,创建已经MyBean类(因为map属性需要从数据库中加载,故需i要实现set方法)
MyBean.java
package bean;
import java.util.Map;
/**
* Created by yuyufeng on 2016/11/17.
*/
public class MyBean {
private Map<String,String> map;
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
然后,配置bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myBean" class="bean.MyBean">
<property name="map">
<map>
<entry key="s01" value="第一个"></entry>
<entry key="s02" value="第二个"></entry>
<entry key="s03" value="第三个"></entry>
</map>
</property>
</bean>
</beans>
然后编写运行入口类
package spring.ioc;
import bean.MyBean;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* Created by yuyufeng on 2016/11/17.
*/
public class LoadBean {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/application.xml"});
//此时spring容器已经启动,这时我们需要再加载一个bean进去
//在web环境中,我们也可以轻松得或得到当前Spring容器 context = ContextLoader.getCurrentWebApplicationContext();
//1.首先需要一个spring中从xml加载bean的类XmlBeanDefinitionReader,并关联当前容器
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) context.getAutowireCapableBeanFactory());
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(context));
beanDefinitionReader.loadBeanDefinitions("spring/ioc/bean.xml");
MyBean myBean = (MyBean) context.getBean("myBean");
Map<String, String> map = myBean.getMap();
for (String s : map.keySet()){
System.out.println("## " + s + ":" + map.get(s));
}
}
}
运行结果:
更多推荐
已为社区贡献3条内容
所有评论(0)