根据系统环境的不同,Profile可以用来切换数据源。例如切换开发,测试,生产环境的数据源。

举个例子:

先创建配置类MainProfileConfig:

  1. @Configuration
  2. @PropertySource("classpath:/jdbc.properties")
  3. public class MainProfileConfig implements EmbeddedValueResolverAware {
  4.  
  5. @Value("${db.user}")
  6. private String user;
  7.  
  8. private String driverClass;
  9.  
  10. private StringValueResolver stringValueResolver;
  11.  
  12. @Profile("test")
  13. @Bean("testDataSource")
  14. public DataSource getTestDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
  15. ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  16. comboPooledDataSource.setUser(user);
  17. comboPooledDataSource.setPassword(pwd);
  18. comboPooledDataSource.setDriverClass(driverClass);
  19. return comboPooledDataSource;
  20. }
  21.  
  22. @Profile("dev")
  23. @Bean("devDataSource")
  24. public DataSource getDevDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
  25. ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  26. comboPooledDataSource.setUser(user);
  27. comboPooledDataSource.setPassword(pwd);
  28. comboPooledDataSource.setDriverClass(driverClass);
  29. return comboPooledDataSource;
  30. }
  31.  
  32. @Profile("pro")
  33. @Bean("proDataSource")
  34. public DataSource getproDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
  35. ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  36. comboPooledDataSource.setUser(user);
  37. comboPooledDataSource.setPassword(pwd);
  38. comboPooledDataSource.setDriverClass(driverClass);
  39. return comboPooledDataSource;
  40. }
  41.  
  42. @Override
  43. public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
  44. this.stringValueResolver = stringValueResolver;
  45. driverClass = stringValueResolver.resolveStringValue("${db.driverClass}");
  46. }
  47. }

这里使用@Value和StringValueResolver来给属性赋值

测试:运行的时候设置环境   -Dspring.profiles.active=dev

  1. public class ProFileTest {
  2.  
  3. @Test
  4. public void test(){
  5. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainProfileConfig.class);
  6.  
  7. String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
  8. for (String name : beanNamesForType){
  9. System.out.println(name);
  10. }
  11. applicationContext.close();
  12. }
  13. }

打印输出:

devDataSource

也可以使用代码的方式设置系统环境,创建容器的时候使用无参构造方法,然后设置属性。

  1. @Test
  2. public void test(){
  3. //创建容器
  4. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
  5. //设置需要激活的环境
  6. applicationContext.getEnvironment().setActiveProfiles("test");
  7. //设置主配置类
  8. applicationContext.register(MainProfileConfig.class);
  9. //启动刷新容器
  10. applicationContext.refresh();
  11.  
  12. String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
  13. for (String name : beanNamesForType){
  14. System.out.println(name);
  15. }
  16. applicationContext.close();
  17. }

打印输出:

testDataSource

  1. setActiveProfiles设置环境的时候可以传入多个值,它的方法可以接受多个参数。
  1. public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
  2. void setActiveProfiles(String... var1);

spring中@Profile的作用的更多相关文章

  1. Spring 中bean的作用、定义

    Spring 中bean的作用.定义: 创建一个bean定义,其实质是用该bean定义对应的类来创建真正实例的"配方(recipe)".把bean定义看成一个配方很有意义,它与cl ...

  2. Spring中FactoryBean的作用和实现原理

    BeanFactory与FactoryBean,相信很多刚翻看Spring源码的同学跟我一样很好奇这俩货怎么长得这么像,分别都是干啥用的.BeanFactory是Spring中Bean工厂的顶层接口, ...

  3. spring中的Log4jConfigListener作用和webapp.root的设置

    转:http://blog.sina.com.cn/s/blog_7bbf356c01016wld.html 使用spring中的Log4jConfigListener有如如下好处:     1. 动 ...

  4. Spring中ApplicationContextAware的作用

    ApplicationContextAware 通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法. ...

  5. Spring中depends-on的作用是什么?

    spring的IOC容器负责bean的管理,当实例化一个bean是,spring保证该Bean所依赖的其他bean已经初始化.一般情况下,用<ref>元素建立对其他bean的依赖关系. 比 ...

  6. Spring 中context.start作用

    我们经常会看到 如下代码 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configPath. ...

  7. @Transacitonal注解不生效之spring中expose-proxy的作用与原理

    几年前记得整理过,@Transacitonal注解的方法被另外一个方法调用的时候,事务是不生效的. 如果大量代码已经这么写了,这个时候抽取出去不现实,怎么办呢? 答案就是在<aop:aspect ...

  8. Spring中@Component的作用

    今天在写程序的时候看见一个以前没有见过的注解(@Component),在网上查找过后,经过实践,决定把它记录下来. 1.@controller 控制器(注入服务) 用于标注控制层,相当于struts中 ...

  9. Spring中的TransactionProxyFactoryBean作用及配置(转)

    问: 原文链接 http://blog.csdn.net/cpp_lzth/article/details/6551703 看AOP的时候发现spring中有个org.springframework. ...

随机推荐

  1. [Google Guava] 1.3-常见Object方法

    原文链接 译者: 沈义扬 equals 当一个对象中的字段可以为null时,实现Object.equals方法会很痛苦,因为不得不分别对它们进行null检查.使用Objects.equal帮助你执行n ...

  2. 工作 巧遇 sql 查询 一组数据中 最新的一条

    SELECT * FROM rsl a, (SELECT CODE, max(time_key) time_key FROM rsl GROUP BY CODE ) b WHERE a. CODE = ...

  3. 将vim打造成python开发工具

    1.创建vim插件工作目录 [root@ray ~]# mkdir -p ~/.vim/bundle 2.下载插件 [root@ray ~]# cd ~/.vim/bundle [root@ray b ...

  4. 浏览器console中加入jquery,测试选择元素

    一.chrome浏览器F12打开调试界面,在console中输入(firefox同样可以): var jquery = document.createElement('script'); jquery ...

  5. luogu 2052 [NOI2011]道路修建 BFS序

    据说dfs会爆栈,写一个 BFS 序更新就好了~ #include <bits/stdc++.h> #define N 1000005 #define ll long long #defi ...

  6. 「CQOI2006」简单题 线段树

    「CQOI2006」简单题 线段树 水.区间修改,单点查询.用线段树维护区间\([L,R]\)内的所有\(1\)的个数,懒标记表示为当前区间是否需要反转(相对于区间当前状态),下方标记时懒标记取反即可 ...

  7. redis系列(三):python操作redis

    1.安装包 pip install redis 2.使用 # -*- coding: utf-8 -*- # @Time : 18-12-7 下午4:33 # @Author : Felix Wang ...

  8. MySQl的库操作、表操作和数据操作

    一.库操作 1.1库的增删改查 (1)系统数据库: performance_schema:用来收集数据库服务器的性能参数,记录处理查询时发生的各种事件.锁等现象 mysql:授权库,主要存储系统用户的 ...

  9. W tensorflow/core/platform/cpu_feature_guard.cc:45]

    W tensorflow/core/platform/cpu_feature_guard.cc:] The TensorFlow library wasn't compiled to use SSE3 ...

  10. Echarts-树状图(源码 含flare.json)

    刚刚发现官网实例里边的数据其实在:https://www.echartsjs.com/data/asset/data/flare.json 源码: html: <!DOCTYPE html> ...