在开发过程中遇到的一大挑战就是将应用程序从一个环境部署到另一个环境,Spring为环境相关的bean提供了很好的解决方案。在这个过程中Spring会根据环境决定该创建哪个bean和不创建哪个bean。不过Spring并不是在构建的时候做出这样的决策,而是等到运行时再来确定。 这样的结果就是同一个部署单元(可能是WAR文件)能够适用于所有的环境,没有必要进行重新构建。
2.配置profile bean在3.1版本,Spring引入了bean profile的功能。在Java配置中,可以使用@Profile注解指定某个bean属于哪一个profile。在应用部署到相应的环境中时,只要确保相应的profile处于激活状态就可以执行相关的bean。部分代码如下
package com.myapp;
import ...
@Configuration
public class DataSourceConfig{
@Bean
@Profile("dev") //开发环境使用这个bean,通过嵌入式数据库获得DataSource
public DataSource embeddedDataSource(){
return ...
}
@Bean
@Profile("prod") //生产环境使用这个bean,通过JNDI从容器获取DataSource
public DataSource jndiDataSource()
{
return ...
}
}
注意,没有指定profile的bean始终都会创建,与激活哪个profile没有关系。 同时XML中也可以通过元素的profie属性进行设置,这里就不过多的讲解了。那么问题来了:我们该怎样激活某个profile呢?
3.激活profileSpring在确定哪个profile处于激活状态时,需要依赖两个独立的属性:spring.profiles.active spring.profiles.default 如果设置了spring.profiles.active属性的话,那么它的值就会用来确定哪个profile是激活的。但如果没有设置spring.profiles.active属性,Spring就会查找spring.profiles.default的值。如果两个都没有设置的话,那就没有激活的profile,因此只会创建那些没有定义在profile中的bean。 有多种方式来设置这两个属性:
- 作为DispatcherServlet的初始化参数;
- 作为Web应用的上下文参数;
- 作为JNDI条目;
- 作为环境变量;
- 作为JVM的系统属性
- 在集成测试类上,使用@ActiveProfiles注解设置
例如在Web应用中,设置spring.profiles.default的web.xml文件会如下所示:
关注
打赏
- ArrayList c.toArray might (incorrectly) not return Object[] (see 6260652)
- Spring框架实体bean转json返回前端报错:Null key for a Map not allowed in JSON (use a converting NullKeySerializer
- python将数据写入txt文本文件
- Python学习随笔:使用xlwings读取和操作Execl文件
- org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized t
- ‘gbk‘ codec can‘t decode byte 0x80 in position 2: illegal multibyte sequence
- SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3: truncated \UX
- 关于Mybatis中keyProperty属性
- 解决 Mybatis 报错 org.apache.ibatis.ognl.NoSuchPropertyException: XXXCriteria$Criterion.noValue
- mysql报错 is longer than the server configured value of ‘wait_timeout‘