根据不同的环境来装配不同的bean

企业级开发中,我们一般有多种环境,比如开发环境、测试环境、UAT环境和生产环境。而系统中有些配置是和环境强相关的,比如数据库相关的配置,与其他外部系统的集成等。

如何才能实现一个部署包适用于多种环境呢?

Spring给我们提供了一种解决方案,这便是条件化装配bean的机制。最重要的是这种机制是在运行时决定该注入适用于哪个环境的bean对象,不需要重新编译构建。

下面使用Spring的profile机制实现dataSource对象的条件化装配。

1、给出开发环境、测试环境、生产环境dataSource的不同实现类

说明:此处只为演示条件化装配bean,不做真实数据源对象模拟。

public interface DataSource {
void show();
} public class DevDataSource implements DataSource{ public DevDataSource(){
show();
}
public void show() {
System.out.println("开发环境数据源对象");
}
} public class TestDataSource implements DataSource{ public TestDataSource() {
show();
} public void show() {
System.out.println("测试环境数据源对象");
}
} public class ProDataSource implements DataSource{ public ProDataSource() {
show();
} public void show() {
System.out.println("生产环境数据源对象");
}
}

2、使用profile配置条件化bean

其实profile的原理就是将不同的bean定义绑定到一个或多个profile之中,在将应用部署到不同的环境时,确保对应的profile处于激活状态即可。

这里我们使用JavaConfig的方式配置profile bean

@Configuration
public class DataSourceConfig { @Bean
@Profile("dev")
public DataSource devDataSource(){
return new DevDataSource();
} @Bean
@Profile("test")
public DataSource testDataSource(){
return new TestDataSource();
} @Bean
@Profile("pro")
public DataSource proDataSource(){
return new ProDataSource();
}
}

可以看到我们使用了@Profile注解,将不同环境的bean绑定到了不同的profile中。

3、激活profile

只要上面的两步还不行,我们还必须激活profile,这样Spring会依据激活的哪个profile,来创建并装配对应的bean对象。

激活profile需要两个属性。

spring.profiles.active
spring.profiles.default

可以在web.xml中配置Web应用的上下文参数,来激活profile属性。比如在web.xml中增加如下配置来激活dev的profile:

    <context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>

4、测试条件化装配

使用@ActiveProfiles注解在测试类中激活指定profile。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@ActiveProfiles("dev")
public class TestConditionDataSource { @Autowired
private DataSource dataSource; @Test
public void testDataSource(){
Assert.assertNotNull(dataSource);
} }

输出:

开发环境数据源对象

我们profile换成生产环境的pro试下,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@ActiveProfiles("pro")
public class TestConditionDataSource { @Autowired
private DataSource dataSource; @Test
public void testDataSource(){
Assert.assertNotNull(dataSource);
} }

输出:

生产环境数据源对象

通过spring的profile机制,我们实现了不同环境dataSource数据源对象的条件化装配。比较简单,就两步:1、使用@Profile注解为不同的bean配置profile(当然这里也可以是xml的方式),2、根据不同环境激活不同的profile。

使用@Conditional注解实现条件化的bean

Spring 4.0引入的新注解@Conditional注解,它可以用到带有@Bean注解的方法上,如果给定的条件计算结果为true,就会创建这个bean,否则不创建。

1、我们创建一个helloWorld对象

public class HelloWorld {

    public void sayHello(){
System.out.println("conditional 装配helloworld");
}
}

2、创建配置类

在该配置类中我们首先使用了@PropertySource注解加载了属性文件hello.properties,其次可以看到在helloWorld的bean配置中,除了@Bean注解外,多了一个@Conditional注解,不错,@Conditional注解是我们实现条件化装配bean的核心注解。

@Conditional注解中有一个HelloWorldConditional类,该类定义了我们创建该bean对象的条件。

@Configuration
@PropertySource("classpath:hello.properties")
public class HelloWorldConfig { @Bean
@Conditional(HelloWorldConditional.class)
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

3、创建条件类HelloWorldConditional,需要实现Condition接口。

实现了Condition接口,重写了matches方法,在该方法中我们检测了环境变量中是否有hello属性,如果有就创建。没有则忽略。

注意:hello.properties中属性会存储到spring的Environment对象中,因此我们可以检测到其中的属性是否存在。

public class HelloWorldConditional implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().containsProperty("hello");
}
}

4、测试条件装配

public class HelloWorldConditionTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = applicationContext.getBean("helloWorld",HelloWorld.class);
helloWorld.sayHello();
}
}

开始,我们在hello.properties中增加一条属性,

运行测试示例,会输出:

conditional 装配helloworld

说明此时,bean已成功装配。

如果我们注释掉hello.properties的这行属性。再次运行示例,则会提示bean不存在。



提示没有“helloWorld”的bean对象,说明了条件不满足不会创建bean对象。

总结

Spring条件化装配bean的两种方式,第一种是使用profile机制,在bean的配置类中使用@profile注解,标识哪些bean对应哪个profile配置,然后在web.xml或Servlet启动参数中配置激活哪个profile来实现条件装配;第二种是使用@Conditional注解,在带有@Bean注解的方法上增加@Conditional注解,在注解属性值中提供一个实现了Condition接口的类(该类会重写matches方法,定义具体的创建条件)。<完>

【10分钟学Spring】:@Profile、@Conditional实现条件化装配的更多相关文章

  1. 【10分钟学Spring】:(一)初识Spring框架

    简介 Spring是一个轻量级的企业级的Java开发框架.主要是用来替代原来更加重量级的企业级Java技术,比如EJB(Enterprise JavaBean).Java数据对象(Java Data ...

  2. 【10分钟学Spring】:(二)一文搞懂spring依赖注入(DI)

    Spring最基础的特性就是创建bean.管理bean之间的依赖关系.下面通过具体实例演示该如何装配我们应用中的bean. Spring提供了三种主要的装配机制 在xml中进行显示的配置 在Java中 ...

  3. spring对bean的高级装配之基于@Conditional条件化装配

    上篇介绍了如何基于profile来条件化创建bean,spring会根据profile的激活状态来进行创建;这篇介绍如何基于spring4.0引入的@Conditional和Condition接口来更 ...

  4. Spring入门(六):条件化的bean

    1. 概念 默认情况下,Spring中定义的bean在应用程序启动时会全部装配,不管当前运行的是哪个环境(Dev,QA或者Prod),也不管当前运行的是什么系统(Windows或者Linux),但有些 ...

  5. 带你学够浪:Go语言基础系列 - 10分钟学方法和接口

    文章每周持续更新,原创不易,「三连」让更多人看到是对我最大的肯定.可以微信搜索公众号「 后端技术学堂 」第一时间阅读(一般比博客早更新一到两篇) 对于一般的语言使用者来说 ,20% 的语言特性就能够满 ...

  6. 这是我见过最简单的博客文只有一张图,Python基础10分钟学完

  7. 10分钟了解 pandas - pandas官方文档译文 [原创]

    10 Minutes to pandas 英文原文:https://pandas.pydata.org/pandas-docs/stable/10min.html 版本:pandas 0.23.4 采 ...

  8. Spring Boot自动配置与Spring 条件化配置

    SpringBoot自动配置 SpringBoot的自动配置是一个运行时(应用程序启动时)的过程,简化开发时间,无需浪费时间讨论具体的Spring配置,只需考虑如何利用SpringBoot的自动配置即 ...

  9. MT【164】条件化简

    (2017北大优特测试第9题) 已知实数 \(a_i\)(\(i=1,2,3,4,5\))满足 \((a_1-a_2)^2+(a_2-a_3)^2+(a_3-a_4)^2+(a_4-a_5)^2=1\ ...

随机推荐

  1. AtCoder Grand Contest 038E - Gachapon

    \(\bf Description\) 一个 \(0\) 到 \(n-1\) 的随机数生成器,生成 \(i\) 的概率是 \(A_i/S\) ,其中 \(S=\sum_{i=0}^{n} A_i\) ...

  2. python 读取文件路径

    python 读取文件路径 一定要用绝对路径不能用相对路径 不然读取不出来 <pre>img = cv.imread("F:\\wef\\wef\\jiaoben\\e\\1.j ...

  3. Linux基础命令(二)

    6.cp copy 作用:复制文件 选项: -a 复制目录时使用并且可以保持属性不变,属性:属主,属组,权限 -r 复制目录时使用但是不可以保持属性不变 -p 保持属性不变 注意:其实只需要记一个-a ...

  4. RTX消息提醒工具设计文档

    为什么要做 项目上线后,系统依然由各业务模块负责人自己维护.而后台运行的各种业务服务结果,不能及时反馈到业务负责人.而等到客户反馈时则会太被动.为了能及时发现并解决项目问题,设计了该工具. 可利用资源 ...

  5. ubuntu开机自启动服务

    ubuntu下一个用来管理开机自启动服务的程序,今天在ss vps上安装时老是提示这个错误,百度后,下面的这个方法可行: vi /etc/apt/source.list 输入i,进入Insert模式 ...

  6. 网站搭建-IIS Windows系统搭建网站 (不小心看到自己的密码 - 怎么找回网站记住的密码)

    上一期说到IIS可以用自己喜欢的网站来直接玩,然后得得瑟瑟将自己的博客园账号首页拿过去玩(今天第一天水博客园). 然后自己访问啊,访问啊,然后就一直点啊点的,当然,其实后面的链接都是跳转到博客园里面去 ...

  7. PHP 性能优化 - php.ini 配置

    内存 默认设置 memory_limit = 128M 单个进程可使用的内存最大值,这个值的设定可以从以下几点考虑: 应用的类型.如果是内存集中型应用,可增加该值: 单个 PHP 进程平均消耗的内存, ...

  8. nyoj 14-会场安排问题 (贪心)

    14-会场安排问题 内存限制:64MB 时间限制:3000ms Special Judge: No accepted:9 submit:15 题目描述: 学校的小礼堂每天都会有许多活动,有时间这些活动 ...

  9. pat 1008 Elevator(20 分)

    1008 Elevator(20 分) The highest building in our city has only one elevator. A request list is made u ...

  10. nyoj 26-孪生素数问题(打表)

    26-孪生素数问题 内存限制:64MB 时间限制:3000ms Special Judge: No accepted:10 submit:43 题目描述: 写一个程序,找出给出素数范围内的所有孪生素数 ...