Spring中对象的初始化和销毁
1.对象的初始化
public void init(){ System.out.println("----User的初始化方法----"); }
2.对象的销毁
public void destroy(){ System.out.println("----User的销毁方法----"); }
对应的bean:
注意: "singleton":单例 "prototype":多例 如果是多例模式,则spring容器不负责销毁
<bean name="user" class="cn.edu.xysf.ssm.entity.User" scope="singleton" init-method="init" destroy-method="destroy"></bean>
测试类:
@Test public void lifeCycleTest(){ //1。需要实例化IOC容器,子类 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); //2.从IOC容器中拿到想要的对象 User user1 = (User)context.getBean("user"); System.out.println(user1); //调用容器的关闭方法,利用容器调用对象的销毁方法 context.close(); }
输出结果:
当 scope=singleton
当 scope=prototype
User类:
public class User implements Serializable { //生产一个默认的序列化版本号 private static final long seriaVersionUID=1L; private int id; private String name; private String password; private String phone; private String workId; private String email; public User(int id, String name, String password, String phone, String workId, String email) { this.id = id; this.name = name; this.password = password; this.phone = phone; this.workId = workId; this.email = email; } public User(){ super(); System.out.println("User的无参构造方法"); } public void init(){ System.out.println("----User的初始化方法----"); } public void destroy(){ System.out.println("----User的销毁方法----"); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getWorkId() { return workId; } public void setWorkId(String workId) { this.workId = workId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", name=" + name + + ", password=" + password + + ", phone=" + phone + + ", workId=" + workId + + ", email=" + email + + }; } }