Spring中读取bean配置文件的几种方式

2025-04-14 07:18:06
推荐回答(1个)
回答1:

BeanFactory允许InputStream作为构造函数的参数,也可以org.springframework.core.io.Resource接口。下面这个例子是用ClassPathResource作为参数:

Resource resource = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resource);
ActionBean action = (ActionBean) factory.getBean("actionBean");

如果同一个Bean在配置文件有多个bean的定义,则用下面的方法取得所有的对象:
Resource resource = new ClassPathResource("bean.xml");
ListableBeanFactory factory = new XmlBeanFactory(resource);

Map helloBeans = factory.getBeansOfType(ActionBean.class, false, false);