淺談spring容器中bean的初始化
當(dāng)我們?cè)趕pring容器中添加一個(gè)bean時(shí),如果沒有指明它的scope屬性,則默認(rèn)是singleton,也就是單例的。
例如先聲明一個(gè)bean:
public class People { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
在applicationContext.xml文件中配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"> <bean id="people" class="People" ></bean> </beans>
然后通過spring容器來(lái)獲取它:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); People p1=(People) context.getBean("people"); People p2=(People) context.getBean("people"); System.out.println(p1); System.out.println(p2); } }
運(yùn)行之后可以看出p1和p2輸入的內(nèi)容是一樣的,說(shuō)明spring中的bean是單例的。
如果不想要單例的bean,可以將scope的屬性改為prototype
<bean id="people" class="People" scope="prototype" ></bean>
這樣通過spring容器獲取的bean就不是單例的了。
spring容器默認(rèn)情況下在啟動(dòng)之后就自動(dòng)為所有bean創(chuàng)建對(duì)象,若想要在我們獲取bean時(shí)才創(chuàng)建的話,可以使用lazy-init屬性
該屬性有三個(gè)值defalut,true,false。默認(rèn)是default,該值和false一樣,都是spring容器啟動(dòng)時(shí)就創(chuàng)建bean對(duì)象,當(dāng)指定為true時(shí),
在我們獲取bean時(shí)才創(chuàng)建對(duì)象。
以上這篇淺談spring容器中bean的初始化就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot項(xiàng)目集成日志的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot項(xiàng)目集成日志的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2019-02-02詳解CopyOnWriteArrayList是如何保證線程安全
這篇文章主要為大家介紹了CopyOnWriteArrayList是如何保證線程安全講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Java ArrayList與LinkedList使用方法詳解
Java中容器對(duì)象主要用來(lái)存儲(chǔ)其他對(duì)象,根據(jù)實(shí)現(xiàn)原理不同,主要有3類常用的容器對(duì)象:ArrayList使用數(shù)組結(jié)構(gòu)存儲(chǔ)容器中的元素、LinkedList使用鏈表結(jié)構(gòu)存儲(chǔ)容器中的元素2022-11-11深入詳解Java中synchronized鎖升級(jí)的套路
synchronized鎖是啥?鎖其實(shí)就是一個(gè)對(duì)象,隨便哪一個(gè)都可以,Java中所有的對(duì)象都是鎖,換句話說(shuō),Java中所有對(duì)象都可以成為鎖。本文我們主要來(lái)聊聊synchronized鎖升級(jí)的套路,感興趣的可以收藏一下2023-04-04