原文地址:http://www.mkyong.com/spring/spring-profiles-example/

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment.

In this tutorial, we will show you a Spring @Profile application, which does the following stuff :

  1. Create two profiles – dev and live
  2. If profile “dev” is enabled, return a simple cache manager – ConcurrentMapCacheManager
  3. If profile “live” is enabled, return an advanced cache manager – EhCacheCacheManager
Note

  1. Spring has supported @Profile annotation since version 3.1
  2. @Profile is inside spring-context.jar

Tools used :

  1. Spring 4.1.4.RELEASE
  2. Ehcache 2.9.0
  3. JDK 1.7

1. Spring @Profile Examples

This @Profile annotation can be applied at class level or method level.

1.1 Normal Spring Configuration, enable caching, so that Spring will expect a cache manager at runtime.

AppConfig
package com.mkyong.test;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.*" })
public class AppConfig {
}

1.2 A dev profile, which returns a simple cache manager concurrentMapCacheManager

CacheConfigDev.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; @Configuration
@Profile("dev")
public class CacheConfigDev { private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class); @Bean
public CacheManager concurrentMapCacheManager() {
log.debug("Cache manager is concurrentMapCacheManager");
return new ConcurrentMapCacheManager("movieFindCache");
} }

1.3 A live profile, which returns ehCacheCacheManager

CacheConfigLive.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource; @Configuration
@Profile("live")
public class CacheConfigLive { private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class); @Bean
public CacheManager cacheManager() {
log.debug("Cache manager is ehCacheCacheManager");
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
} @Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
} }
 

2. Enable @Profile

Few code snippets to show you how to enable a Spring profile.

2.1 For non-web application, you can enable a profile via the Spring context environment.

App.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Enable a "live" profile
context.getEnvironment().setActiveProfiles("live");
context.register(AppConfig.class);
context.refresh(); ((ConfigurableApplicationContext) context).close(); }
}

Output

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is ehCacheCacheManager

Or, via the system property like this

App.java
package com.mkyong.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.AbstractEnvironment; public class App { public static void main(String[] args) { //Enable a "dev" profile
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); }
}

Output

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is concurrentMapCacheManager

2.2 For web application, defined a context parameter in web.xml

web.xml
	<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>live</param-value>
</context-param>

2.3 For web application don’t have web.xml, like servlet 3.0+ container

MyWebInitializer.java
package com.mkyong.servlet3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException; public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer { //...
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.profiles.active", "live");
} }

2.4 For Unit Test, uses @ActiveProfiles

CacheManagerTest.java
package com.mkyong.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.cache.CacheManager; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
@ActiveProfiles("dev")
public class CacheManagerTest { @Autowired
private CacheManager cacheManager; @Test
public void test_abc() {
//...
} }
 

3. More…

3.1 Spring @Profile can apply at method level.

AppConfig.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource; @Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.*" })
public class AppConfig { private static final Logger log = LoggerFactory.getLogger(AppConfig.class); @Bean
@Profile("dev")
public CacheManager concurrentMapCacheManager() {
log.debug("Cache manager is concurrentMapCacheManager");
return new ConcurrentMapCacheManager("movieFindCache");
} @Bean
@Profile("live")
public CacheManager cacheManager() {
log.debug("Cache manager is ehCacheCacheManager");
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
} @Bean
@Profile("live")
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
} }

3.2 You can enable multiple profiles.

	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("live", "linux");
//or
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev, windows");
web.xml
	<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>stage, postgresql</param-value>
</context-param>
	@ActiveProfiles({"dev", "mysql","integration"})
        ((ConfigurableEnvironment)context.getEnvironment())
.setActiveProfiles(new String[]{"dev", "embedded"});

Spring Profiles example--转载的更多相关文章

  1. springboot中spring.profiles.include

    springboot中spring.profiles.include的妙用. 我们有这样的一个springboot项目.项目分为开发.测试.生产三个不同阶段(环境),每个阶段都会有db.ftp.red ...

  2. 使用 spring.profiles.active 及 @profile 注解 动态化配置内部及外部配置

    引言:使用 spring.profiles.active 参数,搭配@Profile注解,可以实现不同环境下(开发.测试.生产)配置参数的切换 一.根据springboot的配置文件命名约定,结合ac ...

  3. SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active

    趁今天有时间整理了一下 启动命令为 //开发环境 java -jar app.jar --spring.profiles.active=dev--server.port=8060 //测试环境 jav ...

  4. spring程序打包war,直接通过-jar启动,并指定spring.profiles.active参数控制多环境配置

    备注:spring boot有内嵌tomcat,jar项目可以用java -jar命令启动,war包也可以,且可以直接指定spring.profiles.active参数控制多环境配置 直接指定传参, ...

  5. springboot中spring.profiles.active来引入多个properties文件 & Springboot获取容器中对象

    1.    引入多个properties文件 很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据, ...

  6. Spring.profiles多环境配置最佳实践

    转自:https://www.cnblogs.com/jason0529/p/6567373.html Spring的profiles机制,是应对多环境下面的一个解决方案,比较常见的是开发和测试环境的 ...

  7. spring boot 入门 使用spring.profiles.active来分区配置

    很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据,这时候,我们可以利用profile在不同的环境 ...

  8. spring-boot:run启动时,指定spring.profiles.active

    Maven启动指定Profile通过-P,如mvn spring-boot:run -Ptest,但这是Maven的Profile. 如果要指定spring-boot的spring.profiles. ...

  9. SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active(转)

    趁今天有时间整理了一下 启动命令为 //开发环境 java -jar app.jar --spring.profiles.active=dev--server.port=8060 //测试环境 jav ...

随机推荐

  1. Windows上Python2与Python3同时安装、共存

    一.选择 Python2 还是 Python3?当然是全都要 Python3 虽是未来,不过 Python2 的用户群体仍然膨大,网上有大量优良的项目和模块可供使用,遇到问题也基本可以找到解决方法,推 ...

  2. oracle查询字段大于指定长度的数据

    select * from MES_MACHINE_RECORD t where length(t.bar_code2)<10 ;

  3. redis练习手册<二>快速入门

    Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案. Redis从它的许多竞争继承来的三个主要特点: Redis数据库完全在内存中,使用磁盘仅用 ...

  4. jsapi微信支付v3版

    请看清楚你的微信支付是v2还是v3.在这里整理的是v3的,v2的同学请忽略! 前期准备须要用的是商户证书,用的是p12的.设置api密钥(在微信商户端中设置),还须要在微信公众号中设置jsapi授权文 ...

  5. OpenCASCADE中散乱Edge生成Wire

    OpenCASCADE中散乱Edge生成Wire eryar@163.com Abstract. In OpenCASCADE a wire can be built from any number ...

  6. 想学android进来看看吧~ ~

    我深知学校里面有非常多同学想学习新的知识,而苦于没有指导. 事实上我想说的是,非常多东西须要靠自己,须要借助度娘,谷歌的.当然有人指导是最好的了. 对于刚接触android是不是也想做出像以下的效果: ...

  7. #学习笔记#——JavaScript 数组部分编程(二)

    2.移除数组 arr 中的所有值与 item 相等的元素,直接在给定的 arr 数组上进行操作,并将结果返回 function removeWithoutCopy(arr, item) { if(!A ...

  8. BZOJ4712: 洪水(树链剖分维护Dp)

    Description 小A走到一个山脚下,准备给自己造一个小屋.这时候,小A的朋友(op,又叫管理员)打开了创造模式,然后飞到 山顶放了格水.于是小A面前出现了一个瀑布.作为平民的小A只好老实巴交地 ...

  9. BZOJ 1604 [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居 Treap

    题意:链接 方法: Treap 解析: 前几道资格赛的题水的不行,这道Gold的题就够分量辣. 首先这个曼哈顿距离啥的肯定能做文章,怎么转化是个问题,自己玩了一会没玩出来,就查了查曼哈顿距离的转化,发 ...

  10. 火车票问题.以及x轴连续矩形,最大面积问题

    假设火车有10个站点: 1000个座位 api(1)  -> param  : leftStation, rightStation -> result : cnt             ...