工厂创建之后,会将Spring配置文件中的所有对象都创建完成(饿汉式)。
提高程序运行效率。避免多次IO,减少对象创建时间。(概念接近连接池,一次性创建好,使用时直接获取)
初始化注解、销毁注解
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @PostConstruct //初始化 public void init(){ System.out.println("init method executed"); } @PreDestroy //销毁 public void destroy(){ System.out.println("destroy method executed"); }
单例bean:singleton
随工厂启动创建 ==》 构造方法 ==》 set方法(注入值) ==》 init(初始化) ==》 构建完成 ==》随工厂关闭销毁
多例bean:prototype
被使用时创建 ==》 构造方法 ==》 set方法(注入值) ==》 init(初始化) ==》 构建完成 ==》JVM垃圾回收销毁
User实体类
package com.cos.qf.entity; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.*; public class User { private Integer id; private String password; private String sex; private Integer age; private Date bornDate; private String[] hobbys; private Set<String> phones; private List<String> names; private Map<String,String> countries; private Properties files; @PostConstruct //初始化 public void init(){ System.out.println("被初始化了"); } @PreDestroy //销毁 public void destroy(){ System.out.println("被销毁了"); } public User() { System.out.println("执行了无参构造"); } public void setId(Integer id) { System.out.println("set-id"); this.id = id; } //get和set方法 }
application-config.xml配置文件
<bean id="user" class="com.cos.qf.entity.User" autowire="byType" init-method="init" destroy-method="destroy"> </bean>
测试方法:不能用ClassPathXmlApplicationContext的父类(ApplicationContext)去关闭不然就报错
@Test public void text4() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); ctx.close(); }
结果: