一.单例模式
单例:[启动容器]--->通过构造方法(创建对象)---->调用set方法(注入)--->调用init方法(初始化)----[容器关闭]----->调用destroy方法(销毁)
applicationContext.xml:
<bean id="userService" class="com.by.service.UserServiceImpl"
scope="singleton" init-method="init" destroy-method="destroy">
UserServiceImpl:
/**
* 业务层实现类
*/
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl() {
System.out.println("调用构造方法创建bean...");
}
public void setUserDao(UserDao userDao) {
System.out.println("调用set方法注入值...");
this.userDao = userDao;
}
public void init(){
System.out.println("调用init方法初始化bean...");
}
public void destroy(){
System.out.println("调用destroy方法销毁bean...");
}
public void addUser(){
userDao.addUser();
}
}
测试:
public static void main(String[] args) {
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//关闭容器
ac.close();
}
结果:
二.多例bean
多例:[使用时getBean]--->通过构造方法(创建对象)---->调用set方法(注入)--->调用init方法(初始化)----[jvm垃圾回收]----->调用destroy方法(销毁)
applicationContext.xml:
<bean id="userService" class="com.by.service.UserServiceImpl"
scope="prototype" init-method="init" destroy-method="destroy">
UserServiceImpl:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl() {
System.out.println("调用构造方法创建bean...");
}
public void setUserDao(UserDao userDao) {
System.out.println("调用set方法注入值...");
this.userDao = userDao;
}
public void init(){
System.out.println("调用init方法初始化bean...");
}
public void destroy(){
System.out.println("调用destroy方法销毁bean...");
}
public void addUser(){
userDao.addUser();
}
}
测试:
public static void main(String[] args) {
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//使用对象
ac.getBean("userService");
}
结果: