博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring3系列5-Bean的基本用法
阅读量:7296 次
发布时间:2019-06-30

本文共 7266 字,大约阅读时间需要 24 分钟。

Spring3系列5-Bean的基本用法

本篇讲述了Bean的基本配置方法,以及Spring中怎样运用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如下

  
  

 

 

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

 

 

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

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

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

 

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

 

注意

实际上,’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.        一般方法

lei
txt

 

2.        缩写方法

 

 

3.        ”p” schema

 

注意,这种方法需要在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,如下

 

 

 

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

 

 

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

 

 

注意,以上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情况下的配置如下

 

以上配置中,如果没有指定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情况下的配置如下:

 

 

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

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 lists;    private Set sets;    private Map
maps; private Properties pros; //...此处省略setter和getter}

 

 

1.        List

  
1

 

2.        Set

  
1

 

 

3.        Map

    

  

 

 

4.        Properties

  
admin@nospam.com
support@nospam.com

 

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

1
1
admin@nospam.com
support@nospam.com

 

 

 

 

 

 

 

转载地址:http://jlynm.baihongyu.com/

你可能感兴趣的文章
使用for--each遍历集合
查看>>
MySQL双主+keeplived安装部署说明
查看>>
基于HWND的Win32 UI自动化
查看>>
WebService 入门程序(一)
查看>>
深入计算机系统 练习题2.44 补码运算
查看>>
python 在linux下读取 .xlsx
查看>>
Java 学习 面向对象学习
查看>>
创建一个git仓库
查看>>
理解爬虫原理
查看>>
Linux 多线程
查看>>
iOS“.NET研究”平台应用开发的敏捷设计流程
查看>>
sqlite数据库中自增key的设定,autoincrement 和 rowid
查看>>
【推荐】10款优秀的jQuery图片插件
查看>>
黑帽大会:SCADA系统安全就像一颗“定时炸弹”
查看>>
20165303第九周学习总结
查看>>
sql存储过程中的整形变量和字符串变量
查看>>
WebService 调用三种方法
查看>>
自定义web框架
查看>>
java集合架构(二)——Map
查看>>
课堂实验
查看>>