spring梳理(一)bean装配方式介绍

spring 装配bean有三种基本方式:

  • xml配置方式
  • java config方式
  • 自动装配方式

1. xml配置方式

示例bean:


public class UserInfo {

    private String username;

    public UserInfo() {}
    public UserInfo(List<String> ns) {
        //假装有这个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会依赖其他bean,spring 会根据上下文装入所需依赖。注入依赖的方式主要有构造器注入属性注入两种。

1.1 构造器注入依赖

<?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">
        <!--构造器注入name属性的值为Lily-->
        <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">
        <!--构造器注入值为Lily-->
        <constructor-arg value="Lily"/>
    </bean>
    <bean id="userInfo" class="cn.wyn.ssm.pojo.UserInfo">
        <!--构造器注入的依赖引用自id 为str的bean-->
        <constructor-arg name="name" ref="str"/>
    </bean>
</beans>

如果装入的依赖是集合List类型(其他map类型类似):

<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属性的值对应的是构造函数的参数名。

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">
        <!--通过UserInfo的setUsername()方法注入-->
        <property name="username" value="Lily"/>
    </bean>
    
</beans>

property元素的name的值对应的就是setXxx方法的xxx成员变量。

2. java config 配置方式

java config配置方式是通过注解来配置bean。

示例:

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

    // 方式1:执行setA函数
    @Bean
    public B setB() {
        return new B(setA());
    }

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

使用@Configuration注解注释的类会被标识为一个配置类,相当于把该类作为spring的xml配置文件中的<beans>,该类会作为一个单独的spring容器。

在扫描该配置bean的时候会将其中的带有@Bean注解的方法依次执行配置bean,返回的bean默认使用方法名作为bean的name。依赖注入使用方式2的spring自动注入方式相比方式1更优雅。

获取该容器中的bean:


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

3. 自动装配方式

@Configuration
@ComponentScan
public class DemoConfig {
}

使用了ComponentScan注解自动扫描,@ComponentScan注解如果不设置扫描的包的属性,则默认是扫描DemoConfig类所在包下的带有@Component注解的Bean,并将带有@Autowire和@Resource等注解的成员变量或者方法所需的依赖自动注入。

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

ps:@Configuration注解标注的类其实也是一个Component,因为该注解的定义上标注了@Component注解,所以扫描的时候@Configuration注解也会被包括进去,并自动执行该类中所有@Bean注解的方法来配置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中整合进另一个java config容器

通过@Import注解来实现

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

4.2 在java config 容器中整合进另一个xml 的IOC容器中的bean

通过@ImportResource注解来实现。

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

4.3 在xml 中整合另一个xml 中配置的bean。

通过<import>元素来实现。

<?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 类以bean的形式配置到xml中:

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

但是,很明显这种方法是不对的,因为注解方式是由spring中某些类来实现装配的,使用java config方式会自动配置这些类到容器,但是xml方式不会自动配置这些类,因此,我们需要手动配置这些类。

  • 如果你想使用@Autowired注解,那么就必须事先在xml中声明 AutowiredAnnotationBeanPostProcessor这个Bean
  • 如果想使用@ Resource@ PostConstruct@ PreDestroy等注解就必须在xml中声明CommonAnnotationBeanPostProcessor这个Bean
  • 如果想使用@PersistenceContext注解,就必须在xml中声明PersistenceAnnotationBeanPostProcessor的Bean。
  • 如果想使用 @Required的注解,就必须在xml中声明RequiredAnnotationBeanPostProcessor这个Bean。

不过这些配置都可以直接用一条配置来替代:

<context:annotation-config/>

这条配置会显示的向spring容器添加上面四个bean。

配置如下:

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

但是,还能更简洁

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

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

一条配置解决,还能定义扫描的包。

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容