Spring装配Bean的三种主要方案

2016-08-15  本文已影响1769人  郭之源

这里说的Bean可不是豆子哦,是组件的意思,也就是哪些具有不同功能的类。将不同功能拆分成不同的组建,不仅能降低程序的耦合度,还能大大提升代码复用率。那么下面我们就来看看Spring装配Bean的三种主要方案吧!

1.隐式的Bean发现机制和自动装配

隐式的Bean发现机制,以其编写简单、实现方便的优点,成为企业级项目开发过程中使用最多的Bean装配机制。它主要是通过两步来实现Bean的装配和使用。

package com.cache.service;
import org.springframework.stereotype.Repository;
/**
 * <dl>
 * <dd>Description:功能描述</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年8月11日 下午6:42:54</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Component("dog")
public class Dog {
    public void call(){
        System.out.println("汪汪汪...");
}

再声明一个组建My,使用了组建Dog:

package com.cache.service;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * <dl>
 * <dd>Description:功能描述</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年8月11日 下午6:42:22</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Component("my")
public class My {
    @Autowired(required=true)
    private Dog dog;
    
    public void shout(){
        dog.call();
    }
}

不过组建扫描默认是不启动的,所以我们要配置一下Spring,让它去寻找含有注解@Respository的类,然后为他们创建Bean。

package com.cache.service;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
 * <dl>
 * <dd>Description:功能描述</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年8月11日 下午6:49:55</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 * @ComponentScan(basePackages="com.cache")
 * @ComponentScan(basePackages={"com.package1","com.package2"})
 * @ComponentScan(basePackageClasses={Dog.class,My.class})
 * 以上是三种指定扫描包的方式
 */
@Configuration
//@ComponentScan(basePackages="com.cache")
//@ComponentScan(basePackages={"com.package1","com.package2"})
@ComponentScan(basePackageClasses={Dog.class,My.class})
public class MyConfig {

}

如果你习惯于使用XML进行组件扫描,那么可以使用Spring context命名空间的 <context:component-scan>元素。

<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
    <!-- 自动扫描 --> <!-- 自动扫描指定的包中的类上的注解 -->
    <context:component-scan base-package="com.cache"/>
</beans>

做完这些之后就能使用注入到Spring容器中的Bean了。

2.在Java代码中进行显式装配

通过隐式扫描和自动装配实现Spring的自动配置的方式固然是方便快捷的,但是有些时候自动装配是行不通的,比如,需要使用到第三方库中的组件,这时候是没有办法在第三方类中添加@Component@Autowired注解的,所以这个时候要使用到JavaConfig或Xml的方式进行组件配置了,下面我们先说一下使用JavaConfig的方式配置组件。

package com.cache.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <dl>
 * <dd>Description:功能描述</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年8月11日 下午6:49:55</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */

@Configuration
// @ComponentScan(basePackages="com.cache")
// @ComponentScan(basePackages={"com.package1","com.package2"})
// @ComponentScan(basePackageClasses={Dog.class,My.class})
public class MyConfig {

    @Bean(name = "dog")
    public Dog dog() {
        return new Dog();
    }

    /**
     * 通过构造器注入方式注入
     * @return
     */
    //@Bean(name = "my")
    //public My my() {
    //  return new My(dog());
    //}

    /**
     * 通过get注入方式注入
     * @param dog
     * @return
     */
    @Bean
    public My my(Dog dog) {
        My my = new My(dog);
        my.setDog(dog);
        return my;
    }

}

3. 在XML中进行显示装配

Spring使用XMl装配Bean,已经有很久的历史了,曾经xml是主要装配bean的方式,但现在使用JavaConfig方式装配Bean很受提倡。现在很多企业还是比较习惯使用XML装配组件,下面我们就简单介绍一下使用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"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
    default-lazy-init="true">


</beans>

<beans></beans>标签中可以声明其他的bean和配置。
声明一个简单的bean:
<bean id="dog" class="com.cache.service.Dog" />

Spring中可以使用<constructor-arg>元素和c命名空间对bean进行构造器注入参数:

<bean id="my" class="com.cache.service.My">
  <constructor-arg ref="dog"/>
  <constructor-arg value="Hello World"/>
</bean>
<bean id="my" class="com.cache.service.My"
    c:dog-ref="dog" 
    c:_title="Hello World"/>

也可以使用变量在构造器参数列表中的位置进行注入:

<bean id="my" class="com.cache.service.My"
    c:_0="haha" 
    c:_1="Hello World"/>
<bean id="my" class="com.cache.service.My">
  <constructor-arg ref="dog"/>
  <constructor-arg value="Hello World"/>
  <constructor-arg>
    <list>
      <value>one</value>
      <value>two</value>
      <value>three</value>
      <value>four</value>
    </list>
  </constructor-arg>
  <constructor-arg>
    <set>
      <value>one</value>
      <value>two</value>
      <value>three</value>
      <value>four</value>
    </set>
  </constructor-arg>
  <constructor-arg>
     <map>
        <entry key="shiro.session.uncache" value-ref="sessionUncacheService"/>
        <entry key="wxCfgReloadChannel"> 
            <bean class="com.rocoinfo.rocomall.rest.admin.wx.WxReloadConfigHandler"/>
        </entry>
     </map>
   </constructor-arg>
</bean>

setter注入是特别常用的注入属性的方式,它的基本语法如下:

<bean id="my" class="com.cache.service.My">
    <property name="dog" ref="dog" />
</bean>

同样的setter注入也有替代的命名空间,那就是p元素:

<bean id="my" class="com.cache.service.My" 
    p:dog-ref="dog" />

sertter方式注入字面量、list、set、map:

<bean id="my" class="com.cache.service.My">
    <property name="dog" ref="dog" />
    <property name="title" value="Hello World"/>
    <property name="statusList">
        <list>
          <value>one</value>
          <value>two</value>
          <value>three</value>
          <value>four</value>
        </list>
     </property>
     <property name="prodList">
        <set>
          <value>one</value>
          <value>two</value>
          <value>three</value>
          <value>four</value>
        </set>
     </property>
     <property name="wordbook">
        <map>
          <entry key="one" value="西游记"/>
          <entry key="one" value="红楼梦"/>
          <entry key="one" value="水浒传"/>
          <entry key="one" value="三国演义"/>
        </map>
     </property>
</bean>

当然也可以借助<util></util>元素将list、set、map等在bean外声明:

<util:list id="nameList">
    <value>one</value>
    <value>two</value>
    <value>three</value>
    <value>four</value>
</util:list>

下面四<util>中的子元素:

元素 描述
<util:content> 引用某个类型的public static 域,并将其暴露为bean
<util:list> 创建一个java.util.List类型的bean,其中包含值或引用
<util:set> 创建一个java.util.Set类型的bean,其中包含值或引用
<util:map> 创建一个java.util.Map类型的bean,其中包含值或引用
<util:propertys> 创建一个java.util.Properties类型的bean
<util:property-path> 引用一个bean的属性或内嵌属性,并将其暴露为一个bean

4. 混合配置

使用@Import注解导入其他JavaConfig中的配置
使用@ImportResource导入XML中的配置

package com.cache.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

/**
 * <dl>
 * <dd>Description:功能描述</dd>
 * <dd>Company: 黑科技</dd>
 * <dd>@date:2016年8月11日 下午9:04:20</dd>
 * <dd>@author:Kong</dd>
 * </dl>
 */
@Configuration
@Import(MyConfig.class)//引用其他JavaConfig中的Bean
//@ImportResource("classpath:my-config.xml")//引用XML中配置的Bean
public class MyConfig2 {

    @Bean(name="my")
    public My my(Dog dog){
        
        My my = new My();
        my.setDog(dog);
        return my;
        //return new My(dog);
    }
}

使用<import resource="applicationContext-shiro.xml"/>引入其他XML配置

<import resource="applicationContext-shiro.xml"/>

<bean class="com.cache.Myconfig"/>

通常企业级开发过程中会将两个或更多的装配类或XML文件组合起来,然后使用组建扫描(<context:component-scan>或@ComponentScan)将bean装配到Spring上下文中。到此我们就学完了Spring最核心、也是工作中使用最多的负责管理bean生命周期的Spring容器。

上一篇下一篇

猜你喜欢

热点阅读