工厂创建之后,会将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(); }
结果:
到此这篇关于详解Spring工厂特性的文章就介绍到这了,更多相关Spring工厂特性内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
免责声明:本站发布的内容(图片、视频和文字)以原创、来自互联网转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系QQ:712375056 进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
Copyright © 2009-2021 56dr.com. All Rights Reserved. 特网科技 特网云 版权所有 珠海市特网科技有限公司 粤ICP备16109289号
域名注册服务机构:阿里云计算有限公司(万网) 域名服务机构:烟台帝思普网络科技有限公司(DNSPod) CDN服务:阿里云计算有限公司 中国互联网举报中心 增值电信业务经营许可证B2
建议您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流浏览器浏览本网站