Spring基础系列5 -- bean的基本用法

Spring基础系列5 -- bean的基本用法

转载:http://www.cnblogs.com/leiOOlei/p/3532604.html

本篇讲述了Bean的基本配置方法,以及Spring中怎样运用Bean。

主要内容如下:

一、      Spring中Bean的相互引用

二、      Spring中给Bean属性注入value

三、      Spring Inner Bean—内部嵌套的Bean

四、      Spring Bean Scopes—Bean的作用域

五、      Spring Collections(List、Set、Map、Properties) — 集合类型的Bean

一、      Spring中Bean的相互引用

在Spring框架中,可以通过ref来互相引用相同或不同xml配置文件中定义的Bean。

1.        引用不同xml配置文件中的bean

如果你想引用不同xml配置文件中的bean,可以使用’ref’标签,结合’bean’属性。

格式:<ref bean="someBean"/>

在下边的例子中,bean’ OutputHelper’在’ Spring-Common.xml’文件中被定义,通过使用’ref’标签,结合’bean’属性,可以引用’ Spring-Output.xml’文件中定义的两个bean(“CsvOutputGenerator” 和 “JsonOutputGenerator“)

配置文件:Spring-Output.xml如下

<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-2.5.xsd">

  <bean id="CsvOutputGenerator"  class="com.lei.output.impl.CsvOutputGenerator" />
  <bean id="JsonOutputGenerator"  class="com.lei.output.impl.JsonOutputGenerator" />

</beans>

配置文件: Spring-Common.xml如下

<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-2.5.xsd">

    <bean id="OutputHelper" class="com.lei.output.OutputHelper">
        <property name="outputGenerator" >
            <ref bean="CsvOutputGenerator"/>
        </property>
    </bean>
</beans>

2.        引用相同xml配置文件中的bean

如果你想引用相同xml配置文件中的bean,可以使用’ref’标签,结合’local’属性。

格式:<ref local="someBean"/>

配置文件:Spring-Output.xml如下

<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-2.5.xsd">

    <bean id="OutputHelper" class="com.lei.output.OutputHelper">
        <property name="outputGenerator" >
            <ref local="CsvOutputGenerator"/>
        </property>
    </bean>
    <bean id="CsvOutputGenerator" class="com.lei.output.impl.CsvOutputGenerator" />
    <bean id="JsonOutputGenerator" class="com.lei.output.impl.JsonOutputGenerator" />

</beans>

注意

实际上,’ref’标签中’bean’属性,既可以引用相同xml文件中的bean,也可以引用不同xml文件中的bean,但是,考虑到项目的可读性,引用相同xml配置文件的bean时,应该尽量使用’local’属性。

二、      Spring中给Bean属性注入value

Spring中,通常有3种方法给Bean的属性注入value。

一般方法,缩写方法,”p” schema方法。

先看下边的Bean:FileNameGenerator.java,其中包含两个properties,name和type,我们向两个properties注入value。

package com.lei.common;

public class FileNameGenerator
{

    private String name;
    private String type;

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

1.        一般方法

<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-2.5.xsd">

    <bean id="FileNameGenerator" class="com.lei.common.FileNameGenerator">
        <property name="name">
            <value>lei</value>
        </property>
        <property name="type">
            <value>txt</value>
        </property>
    </bean>

</beans>

2.        缩写方法

<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-2.5.xsd">

    <bean id="FileNameGenerator" class="com.lei.common.FileNameGenerator">
        <property name="name" value="lei" />
        <property name="type" value="txt" />
    </bean>

</beans>

3.        ”p” schema

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="FileNameGenerator" class="com.lei.common.FileNameGenerator"
             p:name="lei" p:type="txt" />

</beans>

注意,这种方法需要在bean的配置文件xml中,加入以下声明

xmlns:p=”http://www.springframework.org/schema/p

三、      Spring Inner Bean—内部嵌套的Bean

以下Demo演示了一个Bean中嵌套了另一个Bean,即所谓的内部嵌套Bean的配置方法,内部嵌套的Bean支持属性(property)注入和构造函数(constructor-arg)注入。

先看一下Customer.java 和Person.java

package com.lei.common;

public class Customer
{
    private Person person;
    public Customer(Person person) {
        this.person = person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public String toString() {
        return "Customer [person=" + person + "]";
    }
}
package com.lei.common;

public class Person
{
    private String name;
    private String address;
    private int age;

    //getter and setter methods…此处省略

    @Override
    public String toString() {
        return "Person [address=" + address + ",
                               age=" + age + ", name=" + name + "]";
    }
}

配置Bean时,要在Customer的Bean中注入内部Bean,即Person。

1.     Customer中,可以用’ref’属性引用PersonBean,如下

<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-2.5.xsd">

    <bean id="CustomerBean" class="com.lei.common.Customer">
        <property name="person" ref="PersonBean" />
    </bean>

    <bean id="PersonBean" class="com.lei.common.Person">
        <property name="name" value="lei" />
        <property name="address" value="address1" />
        <property name="age" value="28" />
    </bean>

</beans>

2.     以上方法利用’ref’很好的引用了Person,但是,一旦Person仅仅被用在Customer下,也就是说不会被别的Bean引用,最好的方法就是在Customerbean中声明一个内部Bean,如下

<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-2.5.xsd">

    <bean id="CustomerBean" class="com.lei.common.Customer">
        <property name="person">
            <bean class="com.lei.common.Person">
                <property name="name" value="lei" />
                <property name="address" value="address1" />
                <property name="age" value="28" />
            </bean>
        </property>
    </bean>
</beans>

3.     内部Bean也可以通过构造函数注入

<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-2.5.xsd">

    <bean id="CustomerBean" class="com.lei.common.Customer">
        <constructor-arg>
            <bean class="com.lei.common.Person">
                <property name="name" value="lei" />
                <property name="address" value="address1" />
                <property name="age" value="28" />
            </bean>
        </constructor-arg>
    </bean>
</beans>

注意,以上2,3两种情况下,Person的Bean配置中,可以忽略id属性。

四、      Spring Bean Scopes—Bean的作用域

在Spring中,Bean的作用域决定了从Spring容器中返回的Bean实例的类型。

在Spring中,支持以下5中类型的作用域:

  1. singleton — 单例模式,由IOC容器返回一个唯一的bean实例。
  2. prototype — 原型模式,被请求时,每次返回一个新的bean实例。
  3. request — 每个HTTP Request请求返回一个唯一的Bean实例。
  4. session — 每个HTTP Session返回一个唯一的Bean实例。
  5. globalSession — Http Session全局Bean实例。

注:大多数情况下,你可能只需要处理Spring的核心作用域 — 单例模式(singleton)和原型模式(prototype),默认情况下,作用域是单例模式。

singletonprototype区别

CustomerService.java如下

package com.lei.customer.services;

public class CustomerService
{
    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

如果是singleton情况下的配置如下

<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-2.5.xsd">
       <bean id="customerService"
            class="com.lei.customer.services.CustomerService" />
</beans>

以上配置中,如果没有指定scope范围,默认情况下是sighleton模式。

运行下边的代码:

package com.lei.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lei.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
    ApplicationContext context =
     new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

    CustomerService custA = (CustomerService)context.getBean("customerService");
    custA.setMessage("Message by custA");
    System.out.println("Message : " + custA.getMessage());

    //retrieve it again
    CustomerService custB = (CustomerService)context.getBean("customerService");
    System.out.println("Message : " + custB.getMessage());
    }
}

输出结果如下:

Message : Message by custA
Message : Message by custA

Protptype情况下的配置如下:

<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-2.5.xsd">

<bean id="customerService" class="com.lei.customer.services.CustomerService"
         scope="prototype"/>
</beans>

再运行一下测试代码,输出结果如下:

Message : Message by custA
Message : null

设置scope为prototype后,测试代码中,每调用一次getBean()方法后,都会得到一个新的实例。

五、      Spring Collections(List、Set、Map、Properties) — 集合类型的Bean

本节讲述怎样将值注入集合类型,包含以下四种主要的集合类型:

List —— <list/>

Set —— <set/>

Map —— <map/>

Properties —— <props/>

首先写一个Bean,一个Customer对象,包含四种集合属性,如下,

Customer.java

package com.lei.common;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Customer
{
    private List<Object> lists;
    private Set<Object> sets;
    private Map<Object, Object> maps;
    private Properties pros;

    //...此处省略setter和getter
}

1.        List

  <property name="lists">
        <list>
            <value>1</value>
            <ref bean="PersonBean" />
            <bean class="com.lei.common.Person">
                <property name="name" value="leiList" />
                <property name="address" value="address" />
                <property name="age" value="28" />
            </bean>
        </list>
    </property>

2.        Set

  <property name="sets">
        <set>
            <value>1</value>
            <ref bean="PersonBean" />
            <bean class="com.lei.common.Person">
                <property name="name" value="leiSet" />
                <property name="address" value="address" />
                <property name="age" value="28" />
            </bean>
        </set>
    </property>

3.        Map

  <property name="maps">
        <map>
            <entry key="Key 1" value="1" />
            <entry key="Key 2" value-ref="PersonBean" />
            <entry key="Key 3">
                <bean class="com.lei.common.Person">
                    <property name="name" value="leiMap" />
                    <property name="address" value="address" />
                    <property name="age" value="28" />
                </bean>
            </entry>
        </map>
    </property>

4.        Properties

  <property name="pros">
        <props>
            <prop key="admin">[email protected]</prop>
            <prop key="support">[email protected]</prop>
        </props>
    </property>

综上,所有的bean配置文件如下

<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-2.5.xsd">

    <bean id="CustomerBean" class="com.lei.common.Customer">
        <!-- java.util.List -->
        <property name="lists">
            <list>
                <value>1</value>
                <ref bean="PersonBean" />
                <bean class="com.lei.common.Person">
                    <property name="name" value="leiList" />
                    <property name="address" value="address" />
                    <property name="age" value="28" />
                </bean>
            </list>
        </property>

        <!-- java.util.Set -->
        <property name="sets">
            <set>
                <value>1</value>
                <ref bean="PersonBean" />
                <bean class="com.lei.common.Person">
                    <property name="name" value="leiSet" />
                    <property name="address" value="address" />
                    <property name="age" value="28" />
                </bean>
            </set>
        </property>

        <!-- java.util.Map -->
        <property name="maps">
            <map>
                <entry key="Key 1" value="1" />
                <entry key="Key 2" value-ref="PersonBean" />
                <entry key="Key 3">
                    <bean class="com.lei.common.Person">
                        <property name="name" value="leiMap" />
                        <property name="address" value="address" />
                        <property name="age" value="28" />
                    </bean>
                </entry>
            </map>
        </property>

        <!-- java.util.Properties -->
        <property name="pros">
            <props>
                <prop key="admin">[email protected]</prop>
                <prop key="support">[email protected]</prop>
            </props>
        </property>
    </bean>

    <bean id="PersonBean" class="com.lei.common.Person">
        <property name="name" value="lei1" />
        <property name="address" value="address 1" />
        <property name="age" value="28" />
    </bean>

</beans>
时间: 2024-08-09 23:53:41

Spring基础系列5 -- bean的基本用法的相关文章

Spring基础系列8 -- Spring自动装配bean

Spring基础系列8 -- Spring自动装配bean 转载:http://www.cnblogs.com/leiOOlei/p/3548290.html 1.      Auto-Wiring ‘no’ 2.      Auto-Wiring ‘byName’ 3.      Auto-Wiring ‘byType 4.      Auto-Wiring ‘constructor’ 5.      Auto-Wiring ‘autodetect’ Spring Auto-Wiring Be

Spring基础系列7 -- 自动扫描组件或者bean

Spring基础系列7 -- 自动扫描组件或者bean 转载:http://www.cnblogs.com/leiOOlei/p/3547589.html 一.      Spring Auto Scanning Components —— 自动扫描组件 1.      Declares Components Manually——手动配置component 2.      Auto Components Scanning——自动扫描组件 3.      Custom auto scan comp

Spring基础系列11 -- 自动创建Proxy

Spring基础系列11 -- 自动创建Proxy 转载:http://www.cnblogs.com/leiOOlei/p/3557964.html 在<Spring3系列9- Spring AOP——Advice>和<Spring3系列10- Spring AOP——Pointcut,Advisor拦截指定方法>中的例子中,在配置文件中,你必须手动为每一个需要AOP的bean创建Proxy bean(ProxyFactoryBean). 这不是一个好的体验,例如,你想让DAO层

Spring基础系列12 -- Spring AOP AspectJ

Spring基础系列12 -- Spring AOP AspectJ 转载:http://www.cnblogs.com/leiOOlei/p/3613352.html 本文讲述使用AspectJ框架实现Spring AOP. 再重复一下Spring AOP中的三个概念, Advice:向程序内部注入的代码. Pointcut:注入Advice的位置,切入点,一般为某方法. Advisor:Advice和Pointcut的结合单元,以便将Advice和Pointcut分开实现灵活配置. Aspe

Spring基础系列6 -- Spring表达式语言(Spring EL)

Spring基础系列6 -- Spring表达式语言(Spring EL) 转载:http://www.cnblogs.com/leiOOlei/p/3543222.html 本篇讲述了Spring Expression Language —— 即Spring3中功能丰富强大的表达式语言,简称SpEL.SpEL是类似于OGNL和JSF EL的表达式语言,能够在运行时构建复杂表达式,存取对象属性.对象方法调用等.所有的SpEL都支持XML和Annotation两种方式,格式:#{ SpEL exp

Spring基础系列9 -- Spring AOP

Spring基础系列9 -- Spring AOP 转载:http://www.cnblogs.com/leiOOlei/p/3556054.html Spring AOP即Aspect-oriented programming,面向切面编程,是作为面向对象编程的一种补充,专门用于处理系统中分布于各个模块(不同方法)中的交叉关注点的问题.简单地说,就是一个拦截器(interceptor)拦截一些处理过程.例如,当一个method被执行,Spring AOP能够劫持正在运行的method,在met

Spring基础系列10 -- Spring AOP-----------Pointcut, Advisor

Spring基础系列10 -- Spring AOP-----------Pointcut, Advisor 转载:http://www.cnblogs.com/leiOOlei/p/3557643.html 上一篇的Spring AOP Advice例子中,Class(CustomerService)中的全部method都被自动的拦截了.但是大多情况下,你只需要一个方法去拦截一两个method.这样就引入了Pointcut(切入点)的概念,它允许你根据method的名字去拦截指定的method

Spring基础知识及bean的配置

IOC与DI: IOC(inversion of control):其思想是反转资源获取的方向.传统的资源查找方式要求组件向容器发起请求查找资源.作为回应,容器适时的返回资源.而应用了IOC之后,则是容器主动地将资源推送给它所管理的组件,组件所要做的仅是选择一种合适的方式来接收资源.这种方式也被称为查找的被动形式.DI(dependency injection):IOC的另一种表述形式,即组件以一些预先定义好的方式(例如setter方法)接受来自如容器的资源注入.相对于IOC而言,这种表述更直接

Spring基础系列16 -- &lt;context:annotation-config&gt; 和 &lt;context:component-scan&gt;的区别

<context:annotation-config> 和 <context:component-scan>的区别 转载:http://www.cnblogs.com/leiOOlei/p/3713989.html <context:annotation-config> 是用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解. <context:component-scan>除了