目录
spring中基于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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
注释:其中id属性标志单个bean定义的字符串(建议使用类名首字母小写)
class属性定义bean的类型,并且写class的全限定名(也就是把类的包名也带上,此处用反射实现)
单配置文件的引用
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml");
注释:上述代码中可变参数,可写多个配置文件
多配置文件的引用
当你需要引用多个配置文件的时候,此时有两种方法;
方法一:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
注释:使用逗号将配置文件分隔开即可,有多少个写多少个
方法二:
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
注释:多个配置文件通过一个公共的配置文件(all.xml)导入,这样适用于配置文件过多的情况,不易出错
ApplicationContext context = new ClassPathXmlApplicationContext("all.xml");
注释:总的配置文件的名字随意
例子:下面展示一个service.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
如何使用容器
// create and configure beans 得到得到上下文环境
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance 得到PetStoreService对象
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance 通过上一步得到的对象来调用该类的方法
List<String> userList = service.getUsernameList();