1.1.1 XML配置的结构
一般配置文件结构如下:

<beans>
<import resource=”resource1.xml” />
<bean id=”bean1” class=””></bean>
<bean name=”bean2” class=””></bean>
<alias alias="bean3" name="bean2" />
<import resource=”resource2.xml” />
</beans>

1、<bean>标签主要用来进行Bean定义;
2、alias用于定义Bean别名的;
3、import用于导入其他配置文件的Bean定义,这是为了加载多个配置文件,当然也可以把这些配置文件构造为一个数组(new String[] {“config1.xml”, config2.xml})传给ApplicationContext实现进行加载多个配置文件,那一个更适合由用户决定;这两种方式都是通过调用Bean Definition Reader 读取Bean定义,内部实现没有任何区别。<import>标签可以放在<beans>下的任何位置,没有顺序关系。

1.1.2 Bean的配置
Spring IoC容器目的就是管理Bean,这些Bean将根据配置文件中的Bean定义进行创建,而Bean定义在容器内部由BeanDefinition对象表示,该定义主要包含以下信息:
●全限定类名(FQN):用于定义Bean的实现类;
●Bean行为定义:这些定义了Bean在容器中的行为;包括作用域(单例、原型创建)、是否惰性初始化及生命周期等;
●Bean创建方式定义:说明是通过构造器还是工厂方法创建Bean;
●Bean之间关系定义:即对其他bean的引用,也就是依赖关系定义,这些引用bean也可以称之为同事bean或依赖bean,也就是依赖注入。

Bean定义只有“全限定类名”在当使用构造器或静态工厂方法进行实例化bean时是必须的,其他都是可选的定义。难道Spring只能通过配置方式来创建Bean吗?回答当然不是,某些SingletonBeanRegistry接口实现类实现也允许将那些非BeanFactory创建的、已有的用户对象注册到容器中,这些对象必须是共享的,比如使用DefaultListableBeanFactory 的registerSingleton() 方法。不过建议采用元数据定义。

1.1.3 Bean的命名
每个Bean可以有一个或多个id(或称之为标识符或名字),在这里我们把第一个id称为“标识符”,其余id叫做“别名”;这些id在IoC容器中必须唯一。如何为Bean指定id呢,有以下几种方式:
一、不指定id,只配置必须的全限定类名,由IoC容器为其生成一个标识,客户端必须通过接口“T getBean(Class<T> requiredType)”获取Bean;例如:

<bean class=”com.ljq.test.HelloWorldImpl”/>

测试代码片段如下:

@Test
public void sayHello() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("helloworld.xml");
//根据类型获取bean
HelloService helloService = beanFactory.getBean(HelloService.class);
helloService.sayHello();
}

二、指定id,必须在Ioc容器中唯一;例如:

<bean id="helloWorld" class=”com.ljq.test.HelloWorldImpl”/> 

测试代码片段如下:

@Test
public void sayHello() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("helloworld.xml");
//根据id获取bean
HelloService helloService = beanFactory.getBean("helloWorld", HelloService.class);
helloService.sayHello();
}

三、指定name,这样name就是“标识符”,必须在Ioc容器中唯一;例如:

<bean name="helloWorld" class=”com.ljq.test.HelloWorldImpl”/> 

测试代码片段如下:

@Test
public void sayHello() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("helloworld.xml");
//根据name获取bean
HelloService helloService = beanFactory.getBean("helloWorld", HelloService.class);
helloService.sayHello();
}

四、指定id和name,id就是标识符,而name就是别名,必须在Ioc容器中唯一;例如:

<bean id=”bean1” name=”alias1” class=”com.ljq.test.HelloWorldImpl”/>
<!-- 如果id和name一样,IoC容器能检测到,并消除冲突 -->
<bean id="bean3" name="bean3" class=”com.ljq.test.HelloWorldImpl”/>

测试代码片段如下:

@Test
public void sayHello() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("helloworld.xml");
//根据id获取bean
HelloService bean1 = beanFactory.getBean("bean1", HelloService.class);
bean1.sayHello();
//根据别名获取bean
HelloService bean2 = beanFactory.getBean("alias1", HelloService.class);
bean2.sayHello();
//根据id获取bean
HelloService bean3 = beanFactory.getBean("bean3", HelloService.class);
bean3.sayHello();
String[] bean3Alias = beanFactory.getAliases("bean3");
//因此别名不能和id一样,如果一样则由IoC容器负责消除冲突
Assert.assertEquals(0, bean3Alias.length);
}

五、指定多个name,多个name用“,”、“;”、“ ”分割,第一个被用作标识符,其他的(alias1、alias2、alias3)是别名,所有标识符也必须在Ioc容器中唯一;

<bean name=”bean1;alias11,alias12;alias13 alias14”
class=”com.ljq.test.HelloWorldImpl”/>
<!-- 当指定id时,name指定的标识符全部为别名 -->
<bean id="bean2" name="alias21;alias22"
class=”com.ljq.test.HelloWorldImpl”/>

测试代码片段如下:

@Test
public void sayHello() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("helloworld.xml");
//1根据id获取bean
HelloService bean1 = beanFactory.getBean("bean1", HelloService.class);
bean1.sayHello();
//2根据别名获取bean
HelloService alias11 = beanFactory.getBean("alias11", HelloService.class);
alias11.sayHello();
//3验证确实是四个别名
String[] bean1Alias = beanFactory.getAliases("bean1");
System.out.println("=======namingbean5.xml bean1 别名========");
for(String alias : bean1Alias) {
System.out.println(alias);
}
Assert.assertEquals(4, bean1Alias.length);
//根据id获取bean
HelloService bean2 = beanFactory.getBean("bean2", HelloService.class);
bean2.sayHello();
//2根据别名获取bean
HelloService alias21 = beanFactory.getBean("alias21", HelloService.class);
alias21.sayHello();
//验证确实是两个别名
String[] bean2Alias = beanFactory.getAliases("bean2");
System.out.println("=======namingbean5.xml bean2 别名========");
for(String alias : bean2Alias) {
System.out.println(alias);
}
Assert.assertEquals(2, bean2Alias.length);
}

六、使用<alias>标签指定别名,别名也必须在IoC容器中唯一

<bean name="bean" class=”com.ljq.test.HelloWorldImpl”/>
<alias alias="alias1" name="bean"/>
<alias alias="alias2" name="bean"/>

测试代码片段如下:

@Test
public void test6() {
BeanFactory beanFactory =
new ClassPathXmlApplicationContext("chapter2/namingbean6.xml");
//根据id获取bean
HelloService bean = beanFactory.getBean("bean", HelloService.class);
bean.sayHello();
//根据别名获取bean
HelloService alias1 = beanFactory.getBean("alias1", HelloService.class);
alias1.sayHello();
HelloService alias2 = beanFactory.getBean("alias2", HelloService.class);
alias2.sayHello();
String[] beanAlias = beanFactory.getAliases("bean");
System.out.println("=======namingbean6.xml bean 别名========");
for(String alias : beanAlias) {
System.out.println(alias);
}
System.out.println("=======namingbean6.xml bean 别名========");
Assert.assertEquals(2, beanAlias.length);
}

从定义来看,name或id如果指定它们中的一个时都作为“标识符”,那为什么还要有id和name同时存在呢?这是因为当使用基于XML的配置元数据时,在XML中id是一个真正的XML id属性,因此当其他的定义来引用这个id时就体现出id的好处了,可以利用XML解析器来验证引用的这个id是否存在,从而更早的发现是否引用了一个不存在的bean,而使用name,则可能要在真正使用bean时才能发现引用一个不存在的bean。

●Bean命名约定:Bean的命名遵循XML命名规范,但最好符合Java命名规范,由“字母、数字、下划线组成“,而且应该养成一个良好的命名习惯, 比如采用“驼峰式”,即第一个单词首字母开始,从第二个单词开始首字母大写开始,这样可以增加可读性。

1.1.4 实例化Bean
Spring IOC容器如何实例化Bean呢?传统应用程序可以通过new和反射方式进行实例化Bean。而Spring IOC容器则需要根据Bean定义里的配置元数据使用反射机制来创建Bean。在Spring IOC容器中根据Bean定义创建Bean主要有以下几种方式:
一、使用构造器实例化Bean:这是最简单的方式,Spring IOC容器即能使用默认空构造器也能使用有参数构造器两种方式创建Bean,如以下方式指定要创建的Bean类型:

使用空构造器进行定义,使用此种方式,class属性指定的类必须有空构造器

<bean id="helloServiceNoWithArgs" class="com.ljq.test.HelloServiceImpl2" />

使用有参数构造器进行定义,使用此种方式,可以使用<constructor-arg>标签指定构造器参数值,其中index表示位置,value表示常量值,也可以指定引用,指定引用使用ref来引用另一个Bean定义,后边会详细介绍:

<bean id="helloServiceWithArgs" class="com.ljq.test.HelloServiceImpl2">
<!-- 指定构造器参数 -->
<constructor-arg index="0" value="Hello Spring!"/>
</bean>

知道如何配置了,让我们做个例子来实践一下:
a、准备Bean class(HelloWorldImpl2.java),该类有一个空构造器和一个有参构造器:

package com.ljq.test;

public class HelloServiceImpl2 implements HelloService {
private String message; /**
* 空构造器
*/
public HelloServiceImpl2() {
this.message = "Hello World!";
} /**
* 带参构造器
*
* @param message
*/
public HelloServiceImpl2(String message) {
this.message = message;
} public void sayHello() {
System.out.println(message);
}
}

b、在配置文件helloworld.xml配置Bean定义,如下所示:

    <!--使用默认构造参数-->
<bean id="helloServiceNoWithArgs" class="com.ljq.test.HelloServiceImpl2" /> <!--使用有参数构造参数-->
<bean id="helloServiceWithArgs" class="com.ljq.test.HelloServiceImpl2">
<!-- 指定构造器参数 -->
<constructor-arg index="0" value="Hello Spring!"/>
</bean>

c、配置完了,写段测试代码看是否工作:

    /**
* 使用默认构造参数
*/
@Test
public void testHelloWorld2() {
// 1、读取配置文件实例化一个IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloService helloService = context.getBean("helloServiceNoWithArgs", HelloService.class);
// 3、执行业务逻辑
helloService.sayHello();
} /**
* 使用有参数构造参数
*/
@Test
public void testHelloWorld3() {
// 1、读取配置文件实例化一个IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloService helloService = context.getBean("helloServiceWithArgs", HelloService.class);
// 3、执行业务逻辑
helloService.sayHello();
}

二、使用静态工厂方式实例化Bean,使用这种方式除了指定必须的class属性,还要指定factory-method属性来指定实例化Bean的方法,而且使用静态工厂方法也允许指定方法参数,spring IOC容器将调用此属性指定的方法来获取Bean,配置如下所示:
a、先来看看静态工厂类代码HelloApiStaticFactory:

package com.ljq.test;

/**
* 静态工厂类
*
* @author 林计钦
* @version 1.0 2013-11-5 下午10:03:49
*/
public class HelloWorldStaticFactory {
/**
* 工厂方法
*
* @param message
* @return
*/
public static HelloService newInstance(String message) {
// 返回需要的Bean实例
return new HelloServiceImpl2(message);
} }

b、在配置文件helloworld.xml配置Bean定义,如下所示:

    <!--使用有参数构造参数-->
<bean id="helloServiceStaticFactory" class="com.ljq.test.HelloWorldStaticFactory" factory-method="newInstance">
<!-- 指定构造器参数 -->
<constructor-arg index="0" value="Hello Static Factory"/>
</bean>

c、配置完了,写段测试代码看是否工作:

/**
* 使用有参数构造参数
*/
@Test
public void helloServiceStaticFactory() {
// 1、读取配置文件实例化一个IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloService helloService = context.getBean("helloServiceStaticFactory", HelloService.class);
// 3、执行业务逻辑
helloService.sayHello();
}

三、使用实例工厂方法实例化Bean,使用这种方式不能指定class属性,此时必须使用factory-bean属性来指定工厂Bean,factory-method属性指定实例化Bean的方法,而且使用实例工厂方法允许指定方法参数,方式和使用构造器方式一样,配置如下:
a、准备Bean class(HelloWorldImpl2.java),该类有一个空构造器和一个有参构造器:

package com.ljq.test;

/**
* 静态工厂类
*
* @author 林计钦
* @version 1.0 2013-11-5 下午10:03:49
*/
public class HelloWorldStaticFactory { /**
* 工厂方法
*
* @param message
* @return
*/
public HelloService newInstance2(String message) {
// 返回需要的Bean实例
return new HelloServiceImpl2(message);
}
}

b、在配置文件helloworld.xml配置Bean定义,如下所示:

    <!-- 1、定义实例工厂Bean -->
<bean id="beanInstanceFactory" class="com.ljq.test.HelloWorldStaticFactory" />
<!-- 2、使用实例工厂Bean创建Bean -->
<bean id="bean4" factory-bean="beanInstanceFactory" factory-method="newInstance2">
<constructor-arg index="0" value="Hello Spring!"></constructor-arg>
</bean>

c、配置完了,写段测试代码看是否工作:

    @Test
public void helloServiceStaticFactory2() {
// 1、读取配置文件实例化一个IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloService helloService = context.getBean("bean4", HelloService.class);
// 3、执行业务逻辑
helloService.sayHello();
}

通过以上例子我们已经基本掌握了如何实例化Bean了,大家是否注意到?这三种方式只是配置不一样,从获取方式看完全一样,没有任何不同。这也是Spring IOC的魅力,Spring IOC帮你创建Bean,我们只管使用就可以了,是不是很简单。

1.1.5 小结
到此我们已经讲完了Spring IOC基础部分,包括IOC容器概念,如何实例化容器,Bean配置、命名及实例化,Bean获取等等。不知大家是否注意到到目前为止,我们只能通过简单的实例化Bean,没有涉及Bean之间关系。接下来一章让我们进入配置Bean之间关系章节,也就是依赖注入。

---------------------------------------------------------------------------------
Blog:http://www.cnblogs.com/linjiqin/
Hadoop交流群(250363249)、Java+Oracle交流群(158560018)

题外话:
本人来自铁观音的发源地——泉州安溪,有需要正宗安溪铁观音的友友欢迎Q我:416501600。

Spring IOC的配置使用的更多相关文章

  1. Spring IOC的配置使用(转)

    转:http://www.cnblogs.com/linjiqin/p/3408306.html Spring IOC的配置使用 1.1.1 XML配置的结构一般配置文件结构如下: <beans ...

  2. Spring IOC实现配置bean和实例

    配置 beans.xml文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&quo ...

  3. spring ioc xml配置

    一个完整的spring xml配置:是把action,service,dao以及其它的资源性配置(如basedao)和公共性配置(如连接数据库)配置在resource.xml中,这样就有四个xml配置 ...

  4. spring ioc 注解配置

    要注意spring 版本与jdk的兼容性 applicationContext-resource.xml: <beans xmlns="http://www.springframewo ...

  5. Spring Ioc 常用注解

    在开发中spring ioc的配置方式有多种方式,常用的一般都是byName.byType .以及其自动装配可以查看http://www.cnblogs.com/gubai/p/9140840.htm ...

  6. Spring IOC、对象依赖关系

    Spring IOC.对象依赖关系   2016-09-21 01:36 414人阅读 评论(0) 收藏 举报 本文章已收录于: 版权声明:本文为博主原创文章,未经博主允许不得转载. 引入 Strut ...

  7. spring junit--基础配置

    spring官方文档总提示要进行SpringJunit测试必须先配置两个信息: 1.使用Spring IOC功能配置 2.配置正确的JDBC或ORM框架连接数据库 下面进行spring3和hibern ...

  8. 小马哥讲Spring栈核心编程思想 Spring IoC+Bean+Framework

    小马哥出手的Spring栈核心编程思想课程,可以说是非常专业和权威的Spring课程.课程主要的方向与核心是Spring Framework总览,带领同学们重新认识重新认识IoC,Spring IoC ...

  9. Spring学习笔记之三----基于Annotation的Spring IOC配置

    使用Annotation 来创建Bean有两种方式 在配置类中创建bean(配置类是指标注为@Configuration的类),在配置类中每一个创建bean的方法都应该标注为@Bean,可以在@Bea ...

随机推荐

  1. DependencyProperty.UnsetValue 的正确打开方式

    无论是 WPF,还是 UWP,只要你用了绑定或者标记扩展,一定会碰到一个神奇的值——DependencyProperty.UnsetValue.UnsetValue 是什么意思?为什么会出现这个值呢? ...

  2. php中strstr、strchr、strrchr、substr、stristr

    一.strstr 和 strcchr的区别 strstr   显示第一次找到,要查找的字符串,以及后面的字符串. strrchr 显示最后一次找到,要查找的字符串,以及后面的字符串. 二.strstr ...

  3. dda的fpga实现(转载)

    The general approach using DDAs will be to simulate a system of first-order differential equations, ...

  4. p2p通信原理及实现(转)

    1.简介 当今互联网到处存在着一些中间件(MIddleBoxes),如NAT和防火墙,导致两个(不在同一内网)中的客户端无法直接通信.这些问题即便是到了IPV6时代也会存在,因为即使不需要NAT,但还 ...

  5. Go编译安装

    go编译安装: 设置环境变量 # sudo vim /etc/profile.d/go export GOROOT=/home/evescn/go export PATH=$PATH:$GOROOT/ ...

  6. hadoop深入学习之SequenceFile

    的1个byte 3.Key和Value的类名 4.压缩相关的信息 5.其他用户定义的元数据 6.同步标记,sync marker Metadata 在文件创建时就写好了,所以也是不能更改的.条记录存储 ...

  7. Excel信息提取之二

    Sub 订单归纳() Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet Dim dic1 As Object, dic2 As Obje ...

  8. snmpd 子代理模式编译测试

    1.参考链接 1)Net-snmp添加子代理示例 https://blog.csdn.net/eyf0917/article/details/39546651   2.操作步骤 1)网络拷贝下面的文件 ...

  9. Hibernate学习9—检索策略

    本章,采用Class和Student     ——  1 对 多的关系: Student.java: package com.cy.model; public class Student { priv ...

  10. 机器学习:项目流程及方法(以 kaggle 实例解释)

    一.项目目录 (一)数据加载 基础统计 特征分类 基本分布(scatter) (二)数据分析 正态性检验 偏离度分析 (hist | scatter) 峰度分析 (hist | scatter) 分散 ...