Spring IOC控制反转、DI注入以及配置-ref属性表示参照哪个bean对象

<?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">
    <bean id="bookDAO" class="org.itheima.dao.impl.BookDAOImpl"/>
    <bean id="bookService" class="org.itheima.service.impl.BookServiceImpl">
        <property name="bookDAO" ref="bookDAO"/>
    </bean>
</beans>

dao层:

public interface BookDAO {
    public void book();
}
public class BookDAOImpl implements BookDAO {
    @Override
    public void book() {
        System.out.println("BookDAO……");
    }
}

 service层:

public interface BookService {
    public void write();
}

通过容器将bookDAO对象传入进去 

public class BookServiceImpl implements BookService {
    private BookDAO bookDAO;
    @Override
    public void write() {
        bookDAO.book();
        System.out.println("BookService……");
    }
    public void setBookDAO(BookDAO bookDAO) {
        this.bookDAO = bookDAO;
    }
}

测试类:

public class BookServiceImplTest {
private BookService bookService;
    @Test
    public void write() {
        ClassPathXmlApplicationContext cax = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) cax.getBean("bookService");
        bookService.write();
    }
}

测试结果:

4.动态工厂bean的实例化:

DAO层: 

public interface BookDAO {
    public void book();
}

实例化工厂:

public class FactoryImpl implements FactoryBean<BookDAO> {
    @Override
    public BookDAO getObject() throws Exception {
        System.out.println("工厂正在创造DAO对象......");
        return new BookDAOImpl();
    }

    @Override
    public Class<?> getObjectType() {
        return BookDAO.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

 配置文件:

<?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">
    <bean id="bookService" name="service" class="org.itheima.service.impl.BookServiceImpl">
        <property name="bookDAO" ref="bookDAO"/>
    </bean>
    <bean id="bookDAO" class="org.itheima.factory.FactoryImpl"/>
</beans>

 测试文件:

public class BookDAOTest {
    @Test
    public void book() {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDAO bookDAO = (BookDAO) ctx.getBean("bookDAO");
        bookDAO.book();
    }
}

运行结果:

上一篇:运维排查 | Systemd 之服务停止后状态为 failed-问题出现


下一篇:HTML - 请你谈一谈img标签图片和background背景图片的区别