Spring——使用profile为不同环境创建bean
来源:互联网 发布:电子画板手绘软件 编辑:程序博客网 时间:2024/05/24 06:42
0.技术所要解决的问题
在开发软件时候,有一个很大的挑战就是将应用从一个环境迁移到另外一个环境。开发阶段中,某些环境相关做法可能并不合适迁移到生产环境中,甚至迁移过去也无法工作。例如数据库配置,加密算法,外部部署~~
profile bean 可以根据环境选择创建 bean 和不创建哪个 bean。
要使用profile,首先要将所有不同 bean 定义整理到一个或多个 profile 之中,在将应用部署到每个环境时,要确保对应的profile处于激活的状态。程序运行,根据环境不同,决定激活不同的profile,来创建对应的 bean。
1.配置 profile bean
比如下面一个简单的bean对象
@Configuration@Profile("dev")public class test { @Bean(destroyMethod = "shutdown") public DataSource dataSource(){ return new DataSource() { ···· ···· } } }}
@Profile 注解应用在了类级别上。它会告诉 Spring 这个配置类中的 bean 只有在 dev profile 激活时候才会创建。如果 dev profile 没有激活的画,那么带有 @Bean 注解的方法都会被忽略掉。
注意:
- 在Spirng 3.1中,只能在类级别上使用@Profile注解。不过,从Spring 3.2开始你也可以在方法级别上使用@Profile
- 如果没有指定profile的bean始终都会被创建,与激活哪个profile没有关系。
- XML也可以配置profile
2.激活profile
Spirng在确定哪个 profile 处于激活状态时,需要依赖两个独立的属性:spring.profiles.active 和 spring.profiles.default 。
- 如果设置了spring.profiles.active 那么它的值就会用来确定哪个profile是激活的。
- 但如果没有设计 spring.profiles.active 属性的画,那么Spring将会查找spring.profiles.default 的值
- 如果spring.profiles.active 和 spring.profiles.default 均没有设置的画,那就没有激活的profile,因此只会创建那些没有定义profile中的bean。
有多种方式来设置这两个属性:
- 作为 DispatcherServlet 的初始化参数;
- 作为 Web 应用的上下文参数
- 作为 JNDI 条目
- 作为环境变量
- 作为 JVM 的系统属性
- 在集成测试类上,使用 @ActiveProfiles 注解设置
作为简单介绍,这里使用Spring提供的@ActiveProfiles 注解,进行测试时候,需要激活的profile。(个人在写 Web应用但hi后,使用的是第一种与第二种方式结合)
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes={PersistenceTestConfig.class})@ActiveProfiles("dev")public class PersistenceTest{ ···}
参考书目《Spring实战》
阅读全文
0 0
- Spring——使用profile为不同环境创建bean
- Spring-Boot使用profile来配置不同环境的配置文件
- Spring 全注解配置 bean 和 调用 (2) @Profile 自适应不同的模式或环境中
- 根据环境装配你的bean——Spring中profile的应用
- 2--spring bean 的作用域scope 设置;bean的初始化和销毁方法,profile配置不同环境实例化不同的bean,自定义事件,自定义监听器
- 使用maven profile 实现不同环境打包
- 使用Maven和Spring的profile功能实现不同运行环境的无缝切换
- spring注解@Profile的使用案例,并注解测试用例演示,根据不同的条件实例化不同的bean
- 利用spring的profile切换不同的环境
- spring-boot使用profile环境切换
- spring boot 条件注解的使用@Conditional;@Conditional 可以根据条件,创建不同的bean,
- JavaConfig配置文件为Spring创建bean
- spring——bean创建过程
- Spring入门学习——使用Spring的FactoryBean创建Bean
- Maven——profile介绍(不同环境配置不同的参数)
- spring profile来用不同的文件,配置不同的环境, deploy不同的war
- Maven针对不同的环境使用Profile完成打包部署
- Maven针对不同的环境使用Profile完成打包部署
- Qt5.5 使用smtp发邮件的各种坑
- DOM、鼠标、表单、多媒体事件
- springmvc 数据绑定
- Linux CentOS7 简单了解
- 什么是P问题、NP问题和NPC问题
- Spring——使用profile为不同环境创建bean
- @InitBinder注解使用
- llvm存取fs段内容
- 18.关于pom文件中Tomcat插件的设置
- QT5.5 发送忘记密码邮件
- HDU
- Banner无限图片轮播
- mui框架三级城市联动记录
- @ResponseBody 和 @RequestBody 注解的区别