<?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();
}
}
运行结果: