目录
案例
<bean id="userService" class="com.by.service.UserServiceImpl"
scope="singleton" init-method="init" destroy-method="destroy">
/**
* 业务层实现类
*/
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 class Client {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//关闭容器
ac.close();
}
}
生命周期:
[容器启动]--->构造方法(实例化)--->set方法(注入)--->init方法(初始化)--->[容器关闭]--->destroy方法(销毁)
案例
<bean id="userService" class="com.by.service.UserServiceImpl"
scope="prototype" init-method="init" destroy-method="destroy">
/**
* 业务层实现类
*/
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 class Client {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//使用对象
ac.getBean("userService");
}
}
生命周期:
[使用对象]---->构造方法(实例化)--->set方法(注入)--->init方法(初始化)--->[JVM垃圾回收]--->destroy方法(销毁)