App下載

淺談Spring中的設(shè)計(jì)模式之工廠的特性

廢話輸出機(jī)器 2021-08-18 11:37:06 瀏覽數(shù) (1888)
反饋

一、餓漢式創(chuàng)建優(yōu)勢(shì)

工廠創(chuàng)建之后,會(huì)將Spring配置文件中的所有對(duì)象都創(chuàng)建完成(餓漢式)。

提高程序運(yùn)行效率。避免多次IO,減少對(duì)象創(chuàng)建時(shí)間。(概念接近連接池,一次性創(chuàng)建好,使用時(shí)直接獲?。?/p>

二、生命周期方法

  • 自定義初始化方法:添加“init-method”屬性,Spring則會(huì)在創(chuàng)建對(duì)象之后,調(diào)用此方法。
  • 自定義銷毀方法:添加“destroy-method”屬性,Spring則會(huì)在銷毀對(duì)象之前,調(diào)用此方法。
  • 銷毀:工廠的close()方法被調(diào)用之后,Spring會(huì)毀掉所有已創(chuàng)建的單例對(duì)象。
  • 分類:Singleton對(duì)象由Spring容器銷毀、Prototype對(duì)象由JVM銷毀。

三、生命周期注解

初始化注解、銷毀注解

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

隨工廠啟動(dòng)創(chuàng)建 ==》 構(gòu)造方法 ==》 set方法(注入值) ==》 init(初始化) ==》 構(gòu)建完成 ==》隨工廠關(guān)閉銷毀

多例bean:prototype

被使用時(shí)創(chuàng)建 ==》 構(gòu)造方法 ==》 set方法(注入值) ==》 init(初始化) ==》 構(gòu)建完成 ==》JVM垃圾回收銷毀

五、用例

User實(shí)體類

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("執(zhí)行了無(wú)參構(gòu)造");
    }
 
    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>

測(cè)試方法:不能用ClassPathXmlApplicationContext的父類(ApplicationContext)去關(guān)閉不然就報(bào)錯(cuò)

 @Test
    public void text4() {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
        ctx.close();
    }

 

結(jié)果: 

到此這篇關(guān)于Spring工廠特性的文章就介紹到這了,更多相關(guān)Spring工廠模式的內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持!


0 人點(diǎn)贊