<?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="accountDao"
class="com.flydean.daos.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="com.flydean.daos.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
其中id是bean的唯一标记,class是bean的类路径。
实例化容器
Spring容器有很多种实例化方法,比如上面讲的单体应用的两个类:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
上面已经列出了daos.xml , 这里我们再列出services.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="com.flydean.services.PetStoreService">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
<constructor-arg ref="accountDao"/>
</bean>
<!-- more bean definitions for services go here -->
</beans>
GenericApplicationContext context = new GenericApplicationContext();
//reader with xml
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
你也可以使用GroovyBeanDefinitionReader来加载Groovy文件,如下所示:
GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");