bean.xml配置元数据
beans.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>
示例: beans.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="hello" class="com.chen.pojo.Hello">
<!-- collaborators and configuration for this bean go here -->
<!--
value 是基本的值
ref 是引用spring容器中创建好的对象
-->
<property name="name" value="XiaoMing"/>
</bean>
<bean id="userDaoMysql" class="com.chen.dao.UserDaoMysql"/>
<bean id="userDaoOracle" class="com.chen.dao.UserDaoOracle"/>
<bean id="userDaoSqlServer" class="com.chen.dao.UserDaoSqlServer"/>
<bean id="serviceDemo" class="com.chen.service.ServiceDemo">
<!-- collaborators and configuration for this bean go here -->
<!--
value 是基本的值
ref 是引用spring容器中创建好的对象
上面先使spring 生成 userDaoMysql、userDaoOracle、userDaoSqlServer 三个对象
然后再添加 bean serviceDemo,生成 serviceDemo 对象,然后设置属性property,ServiceDemo 类中一定要实现 setUser 方法,
然后ref引用spring容器中创建好的对象
-->
<property name="user" ref="userDaoSqlServer"/>
</bean>
</beans>
MyTest.java
import com.chen.service.ServiceDemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
// Spring 的获取上下文容器,读取beans.xml 配置文件,由 spring 创建、管理对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
ServiceDemo hello = (ServiceDemo) context.getBean("serviceDemo");
hello.getUser();
}
}