1.早期对象创建(什么时候用到,什么时候自己手动创建)
public void testSave1() {
UserDao userDao = new UserDaoImpl();
userDao.save();
}
2.对象由工厂创建(其实这里已经有控制反转的意思,对象创建由手动创建转移到工厂创建)
public class BeanFactory {
public static UserDao getUserDao() {
return new UserDaoImpl(); // 还可以做成配置文件反射做
}
}
public void testSave2() {
UserDao userDao = BeanFactory.getUserDao();
userDao.save();
}
3.具体看看Spring做法
<?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="userDao" class="com.boomsecret.ioc.UserDaoImpl"/>
</beans>
public void testSave3() {
String configPath = "com/boomsecret/ioc/bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configPath);
UserDao userDao = applicationContext.getBean("userDao", UserDao.class);
userDao.save();
}
4.总结
Spring其实就是一个大工厂,可以产生各种Bean