原文地址: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. 紫书 习题 10-44 UVa 11246 ( 容斥原理)

    把k的倍数的删去(k, 2k, 3k--),但是k^2不应该删去,因为k已经删去,所以不存在某个数乘上k之后为k^2 所以k^2可以留下,然后因为有k^2,所以k^3就是k^2的k倍,所以k^3要删去 ...

  2. Swift学习笔记(4)--字符串及基本使用

    String是例如“hello, world”,“海贼王” 这样的有序的Character(字符)类型的值的集合,通过String类型来表示. Swift 的String类型与 Foundation  ...

  3. 使用Microsoft excel 2007 进行数据分析---环境配置

    使用Microsoft excel 2007 进行数据分析---环境配置 使用前须要安装SQL server 2008 data mining Add-ins for Microsoft excel  ...

  4. eXtremeDB相关问题解答(3)

    > 1.         Could our database support multi-database under one single instance? >   > 2. ...

  5. 一些安全的DNS提供商

    检测当前使用的DNS服务器    https://dnsleaktest.com 一些安全的DNS提供商 DNS提供商名称 主DNS服务器 次要DNS服务器 Google 8.8.8.8 8.8.4. ...

  6. linux命令行打开图片

    1.用预装的eog eog a.jpg 2.安装 imagemagick display a.jpg

  7. 2019.05.08 《Linux驱动开发入门与实战》

    第六章:字符设备 申请设备号---注册设备 1.字符设备的框架: 2.结构体,struct cdev: 3.字符设备的组成: 4.例子: 5.申请和释放设备号: 设备号和设备节点是什么关系.? 设备驱 ...

  8. BZOJ3336: Uva10572 Black and White(插头Dp)

    解题思路: 分类讨论即可. 代码(懒得删Debug了): #include<map> #include<cstdio> #include<vector> #incl ...

  9. postgresql 不同数据库不同模式下的数据迁移

    编写不容易,转载请注明出处谢谢, 数据迁移 因为之前爬虫的时候,一部分数据并没有上传到服务器,在本地.本来用的就是postgresql,也没用多久,数据迁移的时候,也遇到了很多问题,第一次使pg_du ...

  10. 【hihocoder 1122】二分图二•二分图最大匹配之匈牙利算法

    [Link]:https://hihocoder.com/problemset/problem/1122 [Description] [Solution] 二分图匹配,匈牙利算法模板题; 这里我先把染 ...