Spring中的Bean<3>

  1. 作用域:
  • singleton:單例模式,在整個(gè)Spring ioc容器中,singleton作用域的bean將只生成一個(gè)示例。
  • prototype:每次通過容器的getBean()方法獲取prototype作用域的bean時(shí),都將產(chǎn)生一個(gè)新的bean實(shí)例。
  • request:對(duì)于依次http請(qǐng)求,request作用域的bean都將只生成一個(gè)實(shí)例,在同一個(gè)http請(qǐng)求,程序每次請(qǐng)求該bean,得到的都是同一個(gè)實(shí)例。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
  • session:對(duì)于一次http會(huì)話,session作用域的bean將只生成一個(gè)實(shí)例,程序每次請(qǐng)求該bean,得到的都是同一個(gè)實(shí)例。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
    -global session:每個(gè)全局的http session對(duì)應(yīng)一個(gè)bean實(shí)例。在典型情況下,僅在使用portlet context的時(shí)候有效。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
    配置分別為sington和prototype
 <bean name="user" class="com.lq.play.model.User" scope="singleton">
        <property name="id" value="32324324"/>
        <property name="username" value="singleton"/>
        <property name="password" value="singleton"/>
        <property name="salt" value="singleton"/>
    </bean>
    <bean name="user1" class="com.lq.play.model.User" scope="prototype">
        <property name="id" value="23443235"/>
        <property name="username" value="prototype"/>
        <property name="password" value="prototype"/>
        <property name="salt" value="prototype"/>
    </bean>

測試代碼

   ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/spring/spring-servlet.xml");
        User user0 = applicationContext.getBean("user", User.class);
        System.out.println(user0);
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);
        User user1 = applicationContext.getBean("user1", User.class);
        System.out.println(user1);
        User user2 = applicationContext.getBean("user1", User.class);
        System.out.println(user2);
        System.out.println(user0==user);
        System.out.println(user1==user2);

輸出結(jié)果

User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
true
false
  1. bean的生命周期
    2.1 Spring提供了兩種方式在bean全部屬性設(shè)置成功后執(zhí)行特定行為
  • 使用init-methd方法
  • 實(shí)現(xiàn)InitializingBean接口,實(shí)現(xiàn)方法
void afterPropertiesSet() throws Exception;

注解使用@PostConstruct
2.2 Spring提供了兩種方式在bean銷毀之前的特定行為,

  • 使用destroy-methd方法
  • 實(shí)現(xiàn)DisposableBean接口,實(shí)現(xiàn)方法
void destroy() throws Exception;

注解使用@PreDestroy

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容