Spring温故而知新 - bean的装配(续)
按条件装配bean
就是当满足特定的条件时Spring容器才创建Bean,Spring中通过@Conditional注解来实现条件化配置bean
package com.sl.ioc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; @Configuration
public class AnimalConfig { @Bean("dog")
@Conditional(DogCondition.class)
public Dog DogInstance() {
return new Dog();
} @Bean("cat")
@Conditional(CatCondition.class)
public Cat CatInstance() {
return new Cat();
} }
@Conditional和 :Condition接口的实现
public @interface Conditional {
/**
* All {@link Condition}s that must {@linkplain Condition#matches match}
* in order for the component to be registered.
*/
Class<? extends Condition>[] value();
}
public interface Condition {
/**
* Determine if the condition matches.
* @param context the condition context
* @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
* or {@link org.springframework.core.type.MethodMetadata method} being checked
* @return {@code true} if the condition matches and the component can be registered,
* or {@code false} to veto the annotated component's registration
*/
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
Conditional注解通过value传入一个类,实现Condition接口,通过实现Condition接口中matches方法决定是否需要装配Bean,如果满足条件需要创建bean则返回true,否则返回false
自己定义两个继承Condition接口的类:通过ConditionContext查找当前环境中是否存在dog或者cat属性,如果存在,则创建对应的bean对象,具体实现如下:
package com.sl.ioc;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata; public class DogCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
boolean flag= environment.containsProperty("dog");
return flag;
}
}
package com.sl.ioc;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class CatCondition implements Condition { @Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); boolean flag= environment.containsProperty("cat"); return flag; }
}
package com.sl.ioc;
import org.springframework.stereotype.Component;
@Component
public interface Animal { void Say(); } package com.sl.ioc;import org.springframework.stereotype.Component; @Component
public class Cat implements Animal {
@Override
public void Say() {
System.out.println("I am a cat");
}
} package com.sl.ioc;
import org.springframework.stereotype.Component; @Component
public class Dat implements Animal {
@Override
public void Say() {
System.out.println("I am a dog");
}
}
测试代码:
public class TestClass {
@Test
public void TestGetDoInstance() {
System.setProperty("dog","");
ApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
String[] beanNames = context.getBeanDefinitionNames();
for(String bean : beanNames) {
System.out.println(bean);
}
}
}
运行测试可以看到输出的beanname中会包含dog的bean:

自动装配的歧义处理
Spring自动装配时如果存在多个bean能够匹配的话,那么这种情况会阻碍Spring通过属性、构造函数或方法进行装配。针对这种情况,Spring提供了多种 可选方案来解决这个问题,可以选择一个bean作为首选的bean,或者使用限定符来确定唯一bean
1 使用首选Bean
Spring提供@Primary注解来设置首选Bean,当初选自动装配歧义时,会选择装配带有@Primary的bean
沿用上面的示例代码,尝试装载animal
@Component
public class AnimalInstance { @Autowired
public Animal animal; }
当Spring尝试注入animal实例时,由于Dog和Cat都继承自Animal,所以此处产生了歧义,下面通过使用@Primary指定首选bean
@Component
@Primary //指定首选bean
public class Cat implements Animal {
@Override
public void Say() {
System.out.println("I am a cat");
}
}
同样也可以使用XML配置来实现:<bean>元素提供了primary属性来设置首选bean
<bean id="cat" class="com.sl.ioc.Cat" primary ="true" >
测试代码:
public class TestClass {
@Test
public void TestGetDoInstance() {
//应用上下文
ApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
AnimalInstance animalInstance = context.getBean(AnimalInstance.class);
animalInstance.animal.Say();
}
}
运行结果:

首选项只是标识一个优先选择装载的bean,如果配置了多个@Primary,那么将带来新的歧义,Spring依然无法完成自动装配,可以通过下面限定符来解决这个问题
2 使用限定符
Spring提供@Qualifier注解来指定想要注入的具体bean。例如上面的示例,如果指定注入dog:
package com.sl.ioc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; @Component
public class AnimalInstance { @Autowired
@Qualifier("dog")
public Animal animal; }
解释一下:@Qualifier("dog")表示指定的bean具有”dog”限定符,spring中bean如果没有指定限定符,会使用默认限定符,即使用beanID作为限定符。所以上面是恰好使用了dog bean的ID作为了限定符。也可以写成如下方式:
@Component
@Qualifier("specialdog") //为bean指定限定符
public class Dog implements Animal
{
@Override
public void Say() {
System.out.println("I am a dog");
}
}
@Component
public class AnimalInstance { @Autowired
@Qualifier("specialdog") //使用上面定义的限定符
public Animal animal;
}
Bean的作用域
Spring容器在创建bean实例的同时,还允许指定bean实例的作用域,常见作用域有一下几种:
1:单例作用域(Singleton)
2:原型作用域(Prototype)
3:会话作用域(Session)
4:请求作用域(Request)
5:全局会话作用域(globalSession)
Singleton作用域
在整个应用中,Spring IOC容器为使用singleton模式的bean只创建一个实例,Spring将会缓存Bean实例,任何对该类型beand请求都会返回该实例。单例也是Spring默认的作用域。具体使用如下,通过XML配置
<bean id="beanid" class="com.sl.ioc.xxx" scope="singleton" ></bean>
<bean>元素提供了scope属性来设置singleton作用域
对应的注解:
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
Prototype原型作用域
每次注入或者从Spring容器中获取时都创建一个新的bean实例:
<bean id="beanid" class="com.sl.ioc.xxx" scope="prototype" ></bean>
<bean>元素提供了scope属性来设置singleton作用域
对应的注解:
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Session会话作用域
在web应用中,针对每个会话,Spring容器根据bean定义创建的bean实例,只在当前会话Session中有效,XML配置如下:
<bean id="beanid" class="com.sl.ioc.xxx" scope="session" ></bean>
针对某个HTTP Session,Spring容器会根据bean定义创建一个新的bean实例,该bean仅在当前HTTP Session内有效。所以可以根据需要放心的更改bean实例的内部状态,而不影响其他Http Session中bean实例。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被销毁掉。
Request 请求作用域
<bean id="beanid" class="com.sl.ioc.xxx" scope="globalSession" ></bean>
在web应用中,针对每次请求,Spring容器根据bean定义创建新的bean实例,只在当前请求内有效
<bean id="beanid" class="com.sl.ioc.xxx" scope="request" ></bean>
该bean实例只在当前请求内有效,在请求处理完成之后bean也会被销毁掉
globalSession全局会话作用域
类似于session作用域,只是其用于portlet环境的web应用。如果在非portlet环境将视为session作用域。
Spring温故而知新 - bean的装配(续)的更多相关文章
- Spring温故而知新 - bean的装配
Spring装配机制 Spring提供了三种主要的装配机制: 1:通过XML进行显示配置 2:通过Java代码显示配置 3:自动化装配 自动化装配 Spring中IOC容器分两个步骤来完成自动化装配: ...
- Spring温故而知新 – bean的装配
Spring装配机制 Spring提供了三种主要的装配机制: 1:通过XML进行显示配置 2:通过Java代码显示配置 3:自动化装配 自动化装配 Spring中IOC容器分两个步骤来完成自动化装配: ...
- Spring - 配置Bean - 自动装配 关系 作用域 引用外部属性文件
1 Autowire自动装配1.1 使用:只需在<bean>中使用autowire元素<bean id="student" class="com.kej ...
- Spring 中Bean的装配方式
最近又买了一本介绍SSM框架的书,是由黑马程序员编写的,书上讲的很好理解,边看边总结一下.主要总结一下bean的装配方式. Bean的装配可以理解为依赖系统注入,Bean的装配方式即Bean依赖注入的 ...
- Spring之Bean的装配
一.Bean的装配Bean的装配,即Bean对象的创建.容器根据代码要求创建Bean对象后再传递给代码的过程,称为Bean的装配.1.默认装配方式代码通过getBean()方式从容器获取指定的Bean ...
- Spring ( 三 ) Spring的Bean的装配与生命周期、专用测试
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 一.对象的生命周期 1.IOC之Bean的生命周期 创建带有生命周期方法的bean public cla ...
- java开发两年,连Spring中bean的装配都不知道?你怎么涨薪啊
Spring 1.1.1.1 创建一个bean package com.zt.spring; public class MyBean { private String userName; privat ...
- [spring]spring的bean自动装配机制
7.bean的自动装配 是spring满足bean依赖的一种方式 spring会在上下文中自动寻找,并自动给bean装配属性 spring的装配方式: (1)手动装配 在people类中依赖了cat和 ...
- Spring笔记2——Spring中Bean的装配
1.引言 Spring中,对象无需自己负责查找或创建与其关联的其他对象,而是由容器负责把需要相互协作的对象引用赋予各个对象.创建应用对象之间的协作关系的行为通常称为装配(Wiring),这也是依赖注入 ...
随机推荐
- UNIX网络编程——I/O复用:select和poll函数
我们看到TCP客户同时处理两个输入:标准输入和TCP套接字.我们遇到的问题是就在客户阻塞于(标准输入上)fgets调用,服务器进程会被杀死.服务器TCP虽然正确的给客户TCP发送了一个FIN,但是既然 ...
- Android开发模式之MVC,MVP和MVVM的简单介绍与区别
相信大家对MVC,MVP和MVVM都不陌生,作为三个最耳熟能详的Android框架,它们的应用可以是非常广泛的,但是对于一些新手来说,可能对于区分它们三个都有困难,更别说在实际的项目中应用了,有些时候 ...
- C++ Primer 有感(重载操作符)
1.用于内置类型的操作符,其含义不能改变.也不能为任何内置类型定义额外的新的操作符.(重载操作符必须具有至少一个类类型或枚举类型的操作数.这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含 ...
- Dynamics CRM2013 任务列表添加自定义按钮
任务列表的command bar 上面添加自定义按钮如下 要注意的是此处的列表不是任务实体而是活动实体,如果你是在任务实体的home栏上面加那你永远看不见按钮的显示,但如果是要在任务的表单界面上加按钮 ...
- Dynamics CRM 2013 subgrid刷新后刷新主表单
项目中会遇到这样的需求,会根据subgrid中的数据变化去更新主表单中的某个或多个字段值,一般的做法就是写插件根据subgrid中实体数据的变化在后台更新主表数据库,但后台更新了要反映到前台就得使用刷 ...
- 08_Android中的SimpleAdapter的使用
1 目的界面 2.编写Android清单文件 <?xml version="1.0" encoding="utf-8"?> <manif ...
- java对象大小
Java对象的内存布局:对象头(Header),实例数据(Instance Data)和对齐填充(Padding) 对象头在32位系统上占用8B,64位系统上占16B. 无论是32位系统还是64位系统 ...
- ffdshow 源代码分析 8: 视频解码器类(TvideoCodecDec)
===================================================== ffdshow源代码分析系列文章列表: ffdshow 源代码分析 1: 整体结构 ffds ...
- 《java入门第一季》之java语法部分小案例
到这里举一个小例子把语法部分梳理一下,下一节开始进入java正式基础--面向对象的学习整理. 案例: /* 某个公司采用公用电话传递数据信息,数据是小于8位的整数,为了确保安全, 在传递过程中需要加密 ...
- 【Android 应用开发】Android UI 设计之 TextView EditText 组件属性方法最详细解析
. 作者 :万境绝尘 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/18964835 . TextView 相关类的继承结构 ...