spring梳理(一)bean裝配方式介紹

spring 裝配bean有三種基本方式:

  • xml配置方式
  • java config方式
  • 自動(dòng)裝配方式

1. xml配置方式

示例bean:


public class UserInfo {

    private String username;

    public UserInfo() {}
    public UserInfo(List<String> ns) {
        //假裝有這個(gè)list
    }

    public UserInfo(String name) {
        this.username = name;
    }

    public void setUsername(String name) {
        this.username = username;
    }
}

application.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="userInfo" class="cn.wyn.ssm.pojo.UserInfo"/>
</beans>

一些bean會(huì)依賴(lài)其他bean,spring 會(huì)根據(jù)上下文裝入所需依賴(lài)。注入依賴(lài)的方式主要有構(gòu)造器注入屬性注入兩種。

1.1 構(gòu)造器注入依賴(lài)

<?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="userInfo" class="cn.wyn.ssm.pojo.UserInfo">
        <!--構(gòu)造器注入name屬性的值為L(zhǎng)ily-->
        <constructor-arg name="name" value="Lily"/>
    </bean>
</beans>

也可以在constructor-arg 元素中以ref屬性注入其他配置的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="str" class="java.lang.String">
        <!--構(gòu)造器注入值為L(zhǎng)ily-->
        <constructor-arg value="Lily"/>
    </bean>
    <bean id="userInfo" class="cn.wyn.ssm.pojo.UserInfo">
        <!--構(gòu)造器注入的依賴(lài)引用自id 為str的bean-->
        <constructor-arg name="name" ref="str"/>
    </bean>
</beans>

如果裝入的依賴(lài)是集合List類(lèi)型(其他map類(lèi)型類(lèi)似):

<bean class="cn.wyn.ssm.pojo.UserInfo">
        <constructor-arg name="ns">
            <list>
                <ref bean="beanId1"/>
                <ref bean="beanId2"/>
            </list>
        </constructor-arg>
</bean>

constructor-arg元素的name屬性的值對(duì)應(yīng)的是構(gòu)造函數(shù)的參數(shù)名。

1.2 屬性setter方法注入

<?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="userInfo" class="cn.wyn.ssm.pojo.UserInfo">
        <!--通過(guò)UserInfo的setUsername()方法注入-->
        <property name="username" value="Lily"/>
    </bean>
    
</beans>

property元素的name的值對(duì)應(yīng)的就是setXxx方法的xxx成員變量。

2. java config 配置方式

java config配置方式是通過(guò)注解來(lái)配置bean。

示例:

@Configuration
class DemoConfig{
    @Bean
    public A setA() {
        return new A();
    }

    // 方式1:執(zhí)行setA函數(shù)
    @Bean
    public B setB() {
        return new B(setA());
    }

    // 方式2:Spring自動(dòng)注入
    @Bean
    public B setB(A a) {
        return new B(a);
    }
}

使用@Configuration注解注釋的類(lèi)會(huì)被標(biāo)識(shí)為一個(gè)配置類(lèi),相當(dāng)于把該類(lèi)作為spring的xml配置文件中的<beans>,該類(lèi)會(huì)作為一個(gè)單獨(dú)的spring容器。

在掃描該配置bean的時(shí)候會(huì)將其中的帶有@Bean注解的方法依次執(zhí)行配置bean,返回的bean默認(rèn)使用方法名作為bean的name。依賴(lài)注入使用方式2的spring自動(dòng)注入方式相比方式1更優(yōu)雅。

獲取該容器中的bean:


AnnotationConfigApplicationContext context2 = new AnnotationConfigApplicationContext(
                DemoConfig.class);
    context2.getBean("A");//獲取name為A的bean。

3. 自動(dòng)裝配方式

@Configuration
@ComponentScan
public class DemoConfig {
}

使用了ComponentScan注解自動(dòng)掃描,@ComponentScan注解如果不設(shè)置掃描的包的屬性,則默認(rèn)是掃描DemoConfig類(lèi)所在包下的帶有@Component注解的Bean,并將帶有@Autowire和@Resource等注解的成員變量或者方法所需的依賴(lài)自動(dòng)注入。

獲取該IOC容器中的Bean的方法同java config配置的方式。

ps:@Configuration注解標(biāo)注的類(lèi)其實(shí)也是一個(gè)Component,因?yàn)樵撟⒔獾亩x上標(biāo)注了@Component注解,所以?huà)呙璧臅r(shí)候@Configuration注解也會(huì)被包括進(jìn)去,并自動(dòng)執(zhí)行該類(lèi)中所有@Bean注解的方法來(lái)配置Bean。

/**
* Configuration注解源碼
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}


4. 整合使用java config容器中的bean和xml配置容器中的bean

4.1 在java config中整合進(jìn)另一個(gè)java config容器

通過(guò)@Import注解來(lái)實(shí)現(xiàn)

@Configuration
@Import(BConfig.class)
@ComponentScan
public class AConfig {
    //此處省略一些@Bean方法
}

4.2 在java config 容器中整合進(jìn)另一個(gè)xml 的IOC容器中的bean

通過(guò)@ImportResource注解來(lái)實(shí)現(xiàn)。

@Configuration
@ImportResource("classpath:xxx.xml")
@ComponentScan
public class AConfig {
    //此處省略一些@Bean方法。
}

4.3 在xml 中整合另一個(gè)xml 中配置的bean。

通過(guò)<import>元素來(lái)實(shí)現(xià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"
       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">
    <import resource="classpath:xxx.xml"/>
</beans>

4.4 在xml 容器中整合java config中的bean

首先,我們想到的是直接將java config 類(lèi)以bean的形式配置到xml中:

<bean class="cn.wyn.XxxConfig"/>

但是,很明顯這種方法是不對(duì)的,因?yàn)樽⒔夥绞绞怯蓅pring中某些類(lèi)來(lái)實(shí)現(xiàn)裝配的,使用java config方式會(huì)自動(dòng)配置這些類(lèi)到容器,但是xml方式不會(huì)自動(dòng)配置這些類(lèi),因此,我們需要手動(dòng)配置這些類(lèi)。

  • 如果你想使用@Autowired注解,那么就必須事先在xml中聲明 AutowiredAnnotationBeanPostProcessor這個(gè)Bean
  • 如果想使用@ Resource 、@ PostConstruct@ PreDestroy等注解就必須在xml中聲明CommonAnnotationBeanPostProcessor這個(gè)Bean
  • 如果想使用@PersistenceContext注解,就必須在xml中聲明PersistenceAnnotationBeanPostProcessor的Bean。
  • 如果想使用 @Required的注解,就必須在xml中聲明RequiredAnnotationBeanPostProcessor這個(gè)Bean。

不過(guò)這些配置都可以直接用一條配置來(lái)替代:

<context:annotation-config/>

這條配置會(huì)顯示的向spring容器添加上面四個(gè)bean。

配置如下:

<context:anotation-config/>
<bean class="cn.wyn.XxxConfig"/>

但是,還能更簡(jiǎn)潔!

使用<component:scan>可以直接省去在xml中聲明java config 的Bean。

<componet:scan basePackage="cn.wyn"/>

一條配置解決,還能定義掃描的包。

參考

最后編輯于
?著作權(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,268評(píng)論 6 342
  • 本章內(nèi)容: 聲明Bean 構(gòu)造器注入和Setter方法注入 裝配Bean 控制bean的創(chuàng)建和銷(xiāo)毀 任何一個(gè)成功的...
    謝隨安閱讀 1,749評(píng)論 0 9
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,489評(píng)論 2 7
  • 今天早上四點(diǎn)鐘開(kāi)始失眠,這樣的日子有一段時(shí)間了,輾轉(zhuǎn)反側(cè),思考人生。夜,讓人無(wú)限聯(lián)想。黎明前的黑暗好長(zhǎng)好長(zhǎng)。...
    小宇君的口袋閱讀 267評(píng)論 0 0

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