Spring學(xué)習(xí)筆記之bean的基礎(chǔ)知識
Bean:
- 在Spring技術(shù)中是基于組件的
- 最基本了是最常用的單元
- 其實(shí)實(shí)例保存在Spring的容器當(dāng)中
Bean通常被定義在配置文件當(dāng)中,Bean實(shí)例化由Spring的Ioc容器進(jìn)行管理,Bean的實(shí)例可以通過Beanfactory進(jìn)行訪問,實(shí)際上大部分J2EE應(yīng)用,Bean是通過ApplicationContext來訪問的,ApplicationContext是BeanFactory的子接口,功能要比BeanFactory強(qiáng)大許多
在前面得博客依賴注入與控制反轉(zhuǎn)中演示了應(yīng)用spring實(shí)現(xiàn)ioc,在ApplicationContext.xml中有bean的配置,里面只是bean簡單的應(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)識,來確定是哪個(gè)bean,可以讓其他bean中使用id引用。class用來指定是哪個(gè)class。同時(shí)還可以設(shè)置scope屬性,scope有兩種:singleton,non-singelton。singleton:單實(shí)例模式(默認(rèn),構(gòu)造方法為private),整個(gè)Spring的容器中只有一個(gè)共享實(shí)例存在(singleton)。non-singelton:每次請求該bean,Spring容器都會新建立一個(gè)bean實(shí)例,然后返回給程序(request,session,prototype)。
二、創(chuàng)建
Bean的命名機(jī)制
id 當(dāng)在Spring的窗口當(dāng)中,查找某個(gè)Bean對象時(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來為bean指定別名.
下面的配置文件還是在上面的xml基礎(chǔ)上修改的。這里配置了ID為ServiceImpl的bean設(shè)置了別名。我們可以使用它的name、id、alias來獲取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元素來設(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;
}
}

對于string類型,XML解析器以String類型解析出數(shù)據(jù),如果屬性不是String類型,屬性值會通過PropertyEditors轉(zhuǎn)換為其他類型,比如時(shí)間類型.
2.注入bean
上面的代碼中就注入了bean,在ServiceImpl中注入DaoImpl??梢允褂胷ef來進(jìn)行配置。
3.注入集合
常見的集合有l(wèi)ist、map、set、property等,下面的代碼是在ServiceImpl中定義了幾個(gè)屬性,然后在上下文中通過屬性注入進(jìn)去。為了測試,在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.自定義屬性編輯器
對于有一些屬性是沒法注入的,此時(shí)就需要自定義,比如上面說的日期類型。
首先是要定義一個(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)換對象,能過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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
簡單了解java函數(shù)式編碼結(jié)構(gòu)及優(yōu)勢
這篇文章主要介紹了簡單了解java函數(shù)式編碼結(jié)構(gòu)及優(yōu)勢,本文將探討三種下一代 JVM 語言:Groovy、Scala 和 Clojure,比較并對比新的功能和范例,讓 Java 開發(fā)人員對自己近期的未來發(fā)展有大體的認(rèn)識。,需要的朋友可以參考下2019-06-06
java并發(fā)等待條件的實(shí)現(xiàn)原理詳解
這篇文章主要介紹了java并發(fā)等待條件的實(shí)現(xiàn)原理詳解,還是比較不錯(cuò)的,這里分享給大家,供需要的朋友參考。2017-11-11
通過實(shí)例了解java checked和unchecked異常
這篇文章主要介紹了通過實(shí)例了解checked和unchecked異常,Java異常分為兩種類型,checked異常和unchecked異常,另一種叫法是異常和錯(cuò)誤。下面小編就帶大家來一起學(xué)習(xí)一下吧2019-06-06

