3.Bean管理-注入对象属性
Service类
- package Spring5.Service;
- import Spring5.Dao.Dao;
- public class Service {
- private Dao dao;
- public void setDao(Dao dao){
- this.dao=dao;
- }
- public void service(){
- System.out.println("service......");
- dao.dao();
- }
- }
Dao接口
- package Spring5.Dao;
- public interface Dao {
- public void dao();
- }
DaoImp接口实现类
- package Spring5.Dao;
- public class DaoImp implements Dao{
- public void dao(){
- System.out.println("dao......");
- }
- }
bean2.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">
- <!--创建Service和DaoImp对象-->
- <bean id="ser" class="Spring5.Service.Service">
- <!--注入Dao对象用ref-->
- <property name="dao" ref="da"></property>
- </bean>
- <bean id="da" class="Spring5.Dao.DaoImp"></bean>
- </beans>
测试类
- public class TEST {
- //bean管理:注入对象属性
- @Test
- public void testBean2(){
- ApplicationContext context= new ClassPathXmlApplicationContext("bean2.xml");
- Service service=context.getBean("ser",Service.class);
- service.service();
- }
- }
测试结果
- service......
- dao......