3.Bean管理-注入对象属性.md

zhanglei 2022年05月30日 381次浏览

3.Bean管理-注入对象属性

Service类

  1. package Spring5.Service;

  2. import Spring5.Dao.Dao;

  3. public class Service {
  4. private Dao dao;
  5. public void setDao(Dao dao){
  6. this.dao=dao;
  7. }
  8. public void service(){
  9. System.out.println("service......");
  10. dao.dao();
  11. }
  12. }

Dao接口

  1. package Spring5.Dao;

  2. public interface Dao {
  3. public void dao();
  4. }

DaoImp接口实现类

  1. package Spring5.Dao;

  2. public class DaoImp implements Dao{
  3. public void dao(){
  4. System.out.println("dao......");
  5. }
  6. }

bean2.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  5. <!--创建Service和DaoImp对象-->
  6. <bean id="ser" class="Spring5.Service.Service">
  7. <!--注入Dao对象用ref-->
  8. <property name="dao" ref="da"></property>
  9. </bean>

  10. <bean id="da" class="Spring5.Dao.DaoImp"></bean>
  11. </beans>

测试类

  1. public class TEST {
  2. //bean管理:注入对象属性
  3. @Test
  4. public void testBean2(){
  5. ApplicationContext context= new ClassPathXmlApplicationContext("bean2.xml");
  6. Service service=context.getBean("ser",Service.class);
  7. service.service();
  8. }
  9. }

测试结果

  1. service......
  2. dao......