Spring Bean裝配之各裝配項 XML實現(xiàn)和注解實現(xiàn)

一、Bean管理的XML配置實現(xiàn)

1.Bean的配置項

  • Id:Bean的唯一標(biāo)識
  • Class:對應(yīng)實現(xiàn)的類
  • Scope:范圍
  • Constructor arguments:構(gòu)造器參數(shù)
  • Properties:屬性
  • Autowiring mode:自動裝配模式
  • lazy-initialization mode:懶加載模式
  • Initialization/destruction method:初始化/銷毀方法

2.Bean的定義

這里以InjectionImpl中包含InjectionDAO成員變量為例,說明設(shè)置注入和構(gòu)造注入,InjectionImpl類如下:

public class InjectionServiceImpl implements InjectionService {
    private InjectionDAO injectionDAO;
}
方式一:設(shè)置注入

bean的XML配置:

<bean id="injectionService" class="com.pinnuli.spring.ioc.injection.service.InjectionServiceImpl">
    <property name="injectionDAO" ref="injectionDAO"></property>
</bean>
<bean id="injectionDAO" class="com.pinnuli.spring.ioc.injection.dao.InjectionDAOImpl"></bean>

InjectionIml中setter方法:

public void setInjectionDAO(InjectionDAO injectionDAO) {
    this.injectionDAO = injectionDAO;
}
方式二:構(gòu)造注入

bean的XML配置:

<bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
    <constructor-arg name="injectionDAO" ref="injectionDAO"></constructor-arg>
</bean>
<bean id="injectionDAO" class="com.pinnuli.spring.ioc.injection.dao.InjectionDAOImpl"></bean>

InjectionIml中構(gòu)造方法:

public InjectionServiceImpl(InjectionDAOImpl injectionDAO) {
    this.injectionDAO = injectionDAO;
}

2.Bean的作用域

  • singleton:單例,一個Bean容器中指存在一份(默認(rèn)情況下為singleton)
  • prototype:每次使用(每次請求,即每次向IOC容器請求獲取一個對象時)都創(chuàng)建新的實例,destroy方法不生效
  • request:每次http請求創(chuàng)建一個實例且僅在當(dāng)前request內(nèi)有效
  • session:同上,每次http請求創(chuàng)建,當(dāng)前session有效
  • global session:給予portel的web中有效,如果是在web中,則同session

XML文件中的配置

<bean id="beanScope" class="com.pinnuli.spring.ioc.bean.BeanScope" scope="singleton"></bean>

3.Bean的生命周期

定義 ? 初始化 ? 使用 ? 銷毀

初始化

方式一:實現(xiàn)org.springframework.beans.factory.InitializingBean借口,覆蓋afterPropertiesSet方法
public class ExampleInitializingBean implements InitialingBean{

    @Override
    public void afterPropertiesSet() throws Exception{
    }
}
方式二:配置init-method

XML文件中的配置:

<bean id="exampleInitBean" class="example.Example" init-method="init"/>

對應(yīng)實現(xiàn)類:

public class ExampleBean{
    public void init(){
    }
}

銷毀:

方式一:實現(xiàn)org.springframework.beans.factory.DisposableBean借口,覆蓋destory方法
public class ExampleInitializingBean implements DisposableBean{

    @Override
    public void destroy() throws Exception{
    }
}
方式二:配置destory-method

XML文件中的配置:

<bean id="exampleInitBean" class="example.Example" init-method="destroy"/>

destory方法:

public class ExampleBean{
    public void destroy(){
    }
}

配置全局默認(rèn)初始化、銷毀方法

<?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"
       default-init-method="init" default-destroy-mothod="destroy">
</beans>

i.當(dāng)三種方式同時配置時,實現(xiàn)接口和配置bean初始化/銷毀方法會覆蓋全局默認(rèn)方法,全局默認(rèn)方法會失效;
ii.即使配置了全局方法,在具體實現(xiàn)中依然可以不定義對應(yīng)的方法,不會有任何異?;驁箦e;
iii.一旦配置了bean初始化/銷毀方法,則必須定義對應(yīng)的初始化銷毀方法。

4.Bean的自動裝配

  • No:什么都不操作
  • byname:即<bean>中的id,根據(jù)屬性名自動裝配,
  • byType:即<bean>中的class

i.如果容器中存在一個與制定屬性類型相同的bean,將與該屬性自動裝配;
ii.如果存在多個該類型的bean,則拋出異常,并指出不能使用byType方式進行自動裝配
iii.如果沒有找到匹配的bean,則不進行任何操作
以上兩種情況bean的XML配置如下:

<beans default-autowire="byType"/"byName">
    <bean id="autoWiringService" class="com.pinnuli.spring.ioc.autowiring.AutoWiringService"></bean>

    <bean id="autoWiringDAO" class="com.pinnuli.spring.ioc.autowiring.AutoWiringDAO"></bean>
</beans>
  • Constructor: 應(yīng)用于構(gòu)造器參數(shù),與byType類似,如果容器沒有找到與構(gòu)造器參數(shù)類型一致的bean,則拋出異常

對應(yīng)的類中的構(gòu)造方法和setter方法與設(shè)置注入或構(gòu)造注入一致


二、Bean管理的注解實現(xiàn)

1.用注解實現(xiàn)時,需要配置以下XML文件掃描有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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd" >
        
    <context:annotation-config/>

</beans>
  • <context:annotation-config/>
    僅會查找同一個applicat context中的bean注解,即掃描完成注冊后的bean中方法和成員變量的注解
    通過在基于XML的Spring配置如下標(biāo)簽
  • <context:component-scan>會掃描所有有bean注解的類,并注冊到IOC容器,包含了<context:annotation-config>的全部功能,因而通常只需要使用前者,而不用后者
<context:component-scan base-package="org.example>

base-package表示掃描包下的所有類

2.使用過濾器進行自定義掃描

默認(rèn)情況下,類被自動發(fā)現(xiàn)并注冊bean的條件是:使用了@Component,@Repository,@Service@Controller注解,或者使用@Component的自定義注解,可以通過過濾器修改上述的行為

<beans>
    <context:component-scan base-package="org.example">
        <context:include-filter type="regex" expression=".*Stub.*Respository"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    <context:component-scan/>    
</beans>

還可以使用use-default-filters="false"禁用自動發(fā)現(xiàn)與注冊

Bean的定義

Bean名稱是由BeannameGenerator生成的,默認(rèn)情況下為類名的首字母變?yōu)樾?/p>

@Component,@Repository,@Service,@Controller都有一個那么屬性用于顯示設(shè)置Bean的名稱,如

@Component("beanName")
public class BeanAnnotation {
}

也可自定義命名策略,實現(xiàn)BeanNameGenerator接口,并一定要包含一個無參構(gòu)造器

<beans>
    <context:component-scan base-package="org.example" name-generator="org.example.MyNameGenerator"/>
</beans>

Bean的作用域

通常情況下啟動查找的Spring組件,其scope是singleton,可用@Scope表示scope,

@Scope("prototype")

也可自定義scope策略,實現(xiàn)實現(xiàn)ScopeMetadataResolver接口,并一定要包含一個無參構(gòu)造器

<beans>
    <context:component-scan base-package="org.example" name-generator="org.example.MyScopeResolver"/>
</beans>

對于自動裝配注解,參見Spring Bean裝配之Autowired注解

代理方式

有三個值可選:no,interfaces,targetClass,默認(rèn)情況下為no

可以配置@Scope注解的proxyMode屬性來配置代理方式,即XML配置時的scope-proxy屬性

@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)

可以在XML文件中使用scope-proxy屬性指定代理

<beans>
    <context:component-scan base-package="org.example" scope-proxy="interfaces"/>
</beans>

三、Resource&ResourceLoader

Resource

針對資源文件的統(tǒng)一入口,用于Spring加載資源文件

  • UrlResource:URL對應(yīng)的資源,根據(jù)一個URL地址即可構(gòu)建
  • ClassPathResource:獲取類路徑下的資源文件
  • FileSystemResource:獲取文件系統(tǒng)里面的資源
  • ServletContextResource:ServletContext封裝的資源,用于訪問ServletContext環(huán)境下的資源
  • InputStreamResource:針對于輸入流封裝的資源
  • ByArrayResource:針對于字節(jié)數(shù)組封裝的資源

ResourceLoader

i.所有的application contexts都實現(xiàn)了ResourceLoader接口,即可以通過ApplicationContext獲得Resource實例
ii.使用參數(shù)的前綴說明獲取資源的類型

1.類路徑下的資源文件
Resource resource = applicationContext.getResource("classpath:config.txt");
2.文件系統(tǒng)中的資源
Resource resource = applicationContext.getResource("file:/var/SpringDemo/src/main/resources/config.txt");
3.URL對應(yīng)的資源
Resource resource = applicationContext.getResource("url:httpS://www.pinnuli.com/index.html");

沒有前綴時,取決于ApplicationContext的路徑(之后再添加解釋)

Resource resource = applicationContext.getResource("config.txt");

參閱:
慕課網(wǎng):Spring入門篇

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

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

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