原文地址: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. Android手机使用WIFI及USB建立FTP服务器总结

    想必大家经常在PC和Android之间传输文件,并不是每次都会插USB接口进行文件传输,就算是插上USB接口,还是有个问题,那就是Android打开大容量存储模式之后,经常很多软件就会被强制停止使用, ...

  2. react基础用法一(在标签中渲染元素)

    react基础用法一(渲染元素) 如图所示最简单的变量使用方法 格式 let 变量名称 = 赋值: 渲染格式直接用 {变量名称} 就可以直接渲染到页面 如图所示第二种渲染方法 格式 const 变量名 ...

  3. JavaScript-原型&原型链&原型继承

    JavaScript-原型&原型链&原型继承 JavaScript的原型是一个重要的知识点,很多扩展应用都是从原型出发的.要说原型,我们先简单说一下函数创建过程.上一篇文章用闭包实现类 ...

  4. HOJ——T 1867 经理的烦恼

    http://acm.hit.edu.cn/hoj/problem/view?id=1867 Source : HCPC 2005 Spring   Time limit : 2 sec   Memo ...

  5. CODEVS——T 1404 字符串匹配

    http://codevs.cn/problem/1404/ 时间限制: 1 s  空间限制: 128000 KB  题目等级 : 大师 Master 题解  查看运行结果     题目描述 Desc ...

  6. C# 对Excel操作时,单元格值的读取

    一.Range中Value与Value2的区别 当range("A1:B10")设置为 Currency (货币)和 Date (日期.日期时间)数据类型时,range2将返回对应 ...

  7. android SIM Switch功能和配置

    SIM Switch feature是Smart 3G switch feature在LTE版本号上发展演变而来的功能: MTK双卡双待单通版本号仅仅有一个3/4 G Protocol.所以同一时刻仅 ...

  8. USACO milk

    /* ID:kevin_s1 PROG:milk LANG:C++ */ #include <iostream> #include <string> #include < ...

  9. POJ 2104 K-th Number 静态主席树(裸

    题目链接:点击打开链接 题意: 给定n长的序列.q个询问 以下n个数字给出序列 每一个询问[l, r] k ,输出该区间中第k大的数 先建一个n个节点的空树.然后每次从后往前新建一棵树,依附原来的空树 ...

  10. PAT-中国大学MOOC-陈越、何钦铭-数据结构基础习题集 00-自測4. Have Fun with Numbers (20) 【二星级】

    题目链接:http://www.patest.cn/contests/mooc-ds/00-%E8%87%AA%E6%B5%8B4 题面: 00-自測4. Have Fun with Numbers ...