Spring學(xué)習(xí)筆記之bean的基礎(chǔ)知識(shí)
Bean:
- 在Spring技術(shù)中是基于組件的
- 最基本了是最常用的單元
- 其實(shí)實(shí)例保存在Spring的容器當(dāng)中
Bean通常被定義在配置文件當(dāng)中,Bean實(shí)例化由Spring的Ioc容器進(jìn)行管理,Bean的實(shí)例可以通過(guò)Beanfactory進(jìn)行訪問(wèn),實(shí)際上大部分J2EE應(yīng)用,Bean是通過(guò)ApplicationContext來(lái)訪問(wèn)的,ApplicationContext是BeanFactory的子接口,功能要比BeanFactory強(qiáng)大許多
在前面得博客依賴注入與控制反轉(zhuǎn)中演示了應(yīng)用spring實(shí)現(xiàn)ioc,在ApplicationContext.xml中有bean的配置,里面只是bean簡(jiǎn)單的應(yīng)用。這篇主要是進(jìn)一步學(xué)習(xí)使用bean。
一、定義
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean> <bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton"> <property name="dao" ref="DaoImpl"></property> </bean> </beans>
上面的代碼是之前博客配置的,可以看到bean的基本構(gòu)成。 <beans/>是Sring配置文件的根節(jié)點(diǎn),一個(gè)<beans/>節(jié)點(diǎn)里面可以有多個(gè)<bean>節(jié)點(diǎn)。在bean中常用兩個(gè)屬性:ID,Class. ID是一唯一標(biāo)識(shí),來(lái)確定是哪個(gè)bean,可以讓其他bean中使用id引用。class用來(lái)指定是哪個(gè)class。同時(shí)還可以設(shè)置scope屬性,scope有兩種:singleton,non-singelton。singleton:?jiǎn)螌?shí)例模式(默認(rèn),構(gòu)造方法為private),整個(gè)Spring的容器中只有一個(gè)共享實(shí)例存在(singleton)。non-singelton:每次請(qǐng)求該bean,Spring容器都會(huì)新建立一個(gè)bean實(shí)例,然后返回給程序(request,session,prototype)。
二、創(chuàng)建
Bean的命名機(jī)制
id 當(dāng)在Spring的窗口當(dāng)中,查找某個(gè)Bean對(duì)象時(shí),首先根據(jù)id進(jìn)行查找,將其余作為Bean的默認(rèn)名稱,如果ID屬性不存在,則根據(jù)Name屬性進(jìn)行查找(將其中的第一個(gè)名稱作為默認(rèn)的名稱),如果ID和NAME都不存在根據(jù)類的名稱進(jìn)行查找。id---------->name--------------->類名。
Bean的別名:可以使用alias來(lái)為bean指定別名.
下面的配置文件還是在上面的xml基礎(chǔ)上修改的。這里配置了ID為ServiceImpl的bean設(shè)置了別名。我們可以使用它的name、id、alias來(lái)獲取service。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean> <bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA"> <property name="dao" ref="DaoImpl"></property> </bean> <alias name="ServiceA" alias="ServiceA1"/> </beans>
package Cuiyw.SpringAop;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Cuiyw.Spring.IService.IService;
public class App
{
public static void main( String[] args )
{
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"ApplicationContext.xml"});
BeanFactory factory=context;
IService service=(IService)factory.getBean("ServiceA1");
service.service("Cuiyw ServiceA1");
service=(IService)factory.getBean("ServiceA");
service.service("Cuiyw ServiceA");
service=(IService)factory.getBean("ServiceImpl");
service.service("Cuiyw ServiceImpl");
}
}

三、注入
1.基本類型和string
可以使用value元素來(lái)設(shè)置,在上面的代碼基礎(chǔ)上稍作修改
<property name="baseProperty" value="222"></property>
package Cuiyw.Spring.Service;
import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService;
public class ServiceImpl implements IService{
private IDao dao;
private int baseProperty;
public IDao getDao() {
return dao;
}
public void setDao(IDao dao) {
this.dao = dao;
}
public void service(String name) {
System.out.println(dao.sayHello(name)+" baseProperty:"+getBaseProperty());
}
public int getBaseProperty() {
return baseProperty;
}
public void setBaseProperty(int baseProperty) {
this.baseProperty = baseProperty;
}
}

對(duì)于string類型,XML解析器以String類型解析出數(shù)據(jù),如果屬性不是String類型,屬性值會(huì)通過(guò)PropertyEditors轉(zhuǎn)換為其他類型,比如時(shí)間類型.
2.注入bean
上面的代碼中就注入了bean,在ServiceImpl中注入DaoImpl??梢允褂胷ef來(lái)進(jìn)行配置。
3.注入集合
常見的集合有l(wèi)ist、map、set、property等,下面的代碼是在ServiceImpl中定義了幾個(gè)屬性,然后在上下文中通過(guò)屬性注入進(jìn)去。為了測(cè)試,在DaoImpl中也增加了一個(gè)屬性s。
package Cuiyw.Spring.Dao;
import java.util.Calendar;
import Cuiyw.Spring.IDao.IDao;
public class DaoImpl implements IDao{
public String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public String sayHello(String name) {
int hour=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(hour<6) return "凌晨早,"+name;
if(hour<12)return "早上好,"+name;
if(hour<13)return "中午好,"+name;
if(hour<18)return "下午好,"+name;
return "晚上好,"+name+", s="+s;
}
}
package Cuiyw.Spring.Service;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService;
public class ServiceImpl implements IService{
private IDao dao;
private int baseProperty;
private List<Object> lists;
private Set<Object> sets;
private Map<Object, Object> maps;
private Properties pros;
public IDao getDao() {
return dao;
}
public void setDao(IDao dao) {
this.dao = dao;
}
public void service(String name) {
System.out.println(dao.sayHello(name)+",baseProperty:"+getBaseProperty());
for(int i=0;i<lists.size();i++)
{
Object obj=lists.get(i);
System.out.println(obj.getClass().getName());
}
for(Object obj : sets)
{
System.out.println(obj.getClass().getName());
}
//遍歷maps中的key
for (Object key : maps.keySet()) {
System.out.println("Key = " + key);
}
//遍歷maps中的值
for (Object value : maps.values()) {
System.out.println("Value = " + value);
}
Set<String> pro=pros.stringPropertyNames();
Iterator<String> it=pro.iterator();
while(it.hasNext()){
Object key=it.next();
System.out.println(key+"----"+pros.getProperty((String) key));
}
}
public int getBaseProperty() {
return baseProperty;
}
public void setBaseProperty(int baseProperty) {
this.baseProperty = baseProperty;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Set<Object> getSets() {
return sets;
}
public void setSets(Set<Object> sets) {
this.sets = sets;
}
public Map<Object, Object> getMaps() {
return maps;
}
public void setMaps(Map<Object, Object> maps) {
this.maps = maps;
}
public Properties getPros() {
return pros;
}
public void setPros(Properties pros) {
this.pros = pros;
}
}
主要是注入的配置,在list、map、set屬性中都是配置了一個(gè)基礎(chǔ)類型value=1,兩個(gè)DaoImpl類型。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cyw"></property>
</bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA">
<property name="dao" ref="DaoImpl"></property>
<property name="baseProperty" value="222"></property>
<property name="lists">
<list>
<value>1</value>
<ref bean="DaoImpl" />
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywlists" />
</bean>
</list>
</property>
<property name="sets">
<set>
<value>1</value>
<ref bean="DaoImpl" />
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywsets" />
</bean>
</set>
</property>
<property name="maps">
<map>
<entry key="key1" value="1"></entry>
<entry key="key2" value-ref="DaoImpl"></entry>
<entry key="key3" >
<bean class="Cuiyw.Spring.Dao.DaoImpl">
<property name="s" value="cuiywmaps" />
</bean>
</entry>
</map>
</property>
<property name="pros">
<props>
<prop key="prokey1">prokeyA</prop>
<prop key="prokey2">prokeyB</prop>
</props>
</property>
</bean>
<alias name="ServiceA" alias="ServiceA1"/>
</beans>
執(zhí)行main方法可以看到屬性都注入進(jìn)去了。

4.自定義屬性編輯器
對(duì)于有一些屬性是沒法注入的,此時(shí)就需要自定義,比如上面說(shuō)的日期類型。
首先是要定義一個(gè)繼承PropertyEditorSupport的類,重寫setAsText方法。
package Cuiyw.Spring.Service;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class CustomerProperty extends PropertyEditorSupport {
private String format="yyyy-MM-dd";
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat(format);
//super.setAsText(text);
try {
//轉(zhuǎn)換對(duì)象,能過(guò)setValue方法重新賦值
this.setValue(sdf.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
然后在配置文件配置這個(gè)類
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date" value="Cuiyw.Spring.Service.CustomerProperty"/> </map> </property> </bean>
這里還是在ServiceImpl中增加了一個(gè)java.util.Date類型的date屬性。并在配置文件注入值。
<property name="date" value="2017-12-10"/>
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Java中Druid連接池連接超時(shí)獲取不到連接的解決
這篇文章主要介紹了Java中Druid連接池連接超時(shí)獲取不到連接的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
springboot數(shù)據(jù)庫(kù)操作圖文教程
本文以圖文并茂的形式給大家介紹了springboot數(shù)據(jù)庫(kù)操作,感興趣的朋友一起看看吧2017-07-07
Java實(shí)現(xiàn)的圖片高質(zhì)量縮放類定義與用法示例
這篇文章主要介紹了Java實(shí)現(xiàn)的圖片高質(zhì)量縮放類定義與用法,涉及java針對(duì)圖片的運(yùn)算與轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Java如何實(shí)現(xiàn)http接口參數(shù)和返回值加密
這篇文章主要介紹了Java如何實(shí)現(xiàn)http接口參數(shù)和返回值加密問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
解決Spring Boot 正常啟動(dòng)后訪問(wèn)Controller提示404問(wèn)題
今天小編再次搭建Spring Boot項(xiàng)目的時(shí)候遇到訪問(wèn)Controller報(bào)404錯(cuò)誤,之前都很順利。到底怎么回事呢?下面小編給大家?guī)?lái)了解決Spring Boot 正常啟動(dòng)后訪問(wèn)Controller提示404問(wèn)題,感興趣的朋友一起看看吧2018-08-08
Spring?Boot源碼實(shí)現(xiàn)StopWatch優(yōu)雅統(tǒng)計(jì)耗時(shí)
這篇文章主要為大家介紹了Spring?Boot源碼實(shí)現(xiàn)StopWatch優(yōu)雅統(tǒng)計(jì)耗時(shí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

