Spring-ioc快速入门详解02
bean实例化的三种方式
需要交给SpringIOC管理的对象并不都是自己new的,也就是说不能通过无参构造去实例化.
- 无参构造方法实例化
<bean id="UserDao" class="com.kiui.dao.impl.UserDaoImpl" scope="prototype"/>
- 工厂静态方法实例化
applicationContext.xml注册bean
<bean id="UserDao" class="com.kiui.factory.StaticFactory" factory-method="getUserDao"/>
工厂类
package com.kiui.factory;
import com.kiui.dao.UserDao;
import com.kiui.dao.impl.UserDaoImpl;
/**
* @author Kiui
*/
public class StaticFactory {
public static UserDao getUserDao() {
return new UserDaoImpl();
}
}
- 工厂方法实例化
applicationContext.xml注册bean
<bean id="factory" class="com.kiui.factory.DynamicFactory"/>
<bean id="UserDao" factory-bean="factory" factory-method="getUserDao"/>
工厂类
package com.kiui.factory;
import com.kiui.dao.UserDao;
import com.kiui.dao.impl.UserDaoImpl;
/**
* @author Kiui
*/
public class DynamicFactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
测试代码
package com.kiui.demo;
import com.kiui.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Kiui
*/
public class UserDaoDemo {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("UserDao");
userDao.save();
}
}
控制台:
save running...
|