博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
高级装配小笔记--环境与profile
阅读量:7088 次
发布时间:2019-06-28

本文共 2246 字,大约阅读时间需要 7 分钟。

hot3.png

环境与profile

比如,考虑一下数据库的配置

配置类

@Profile基于激活的profile实现bean的装配

import javax.sql.DataSource;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile;import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;import org.springframework.jndi.JndiObjectFactoryBean;@Configurationpublic class DataSourceConfig {    @Bean(destroyMethod = "shutdown")  @Profile("dev")  public DataSource embeddedDataSource() {    return new EmbeddedDatabaseBuilder()        .setType(EmbeddedDatabaseType.H2)        .addScript("classpath:schema.sql")        .addScript("classpath:test-data.sql")        .build();  }    // 在QA环境中,你也可以选择完全不同的DataSource配置,配置为Common DBCP连接池  @Bean(destroyMethod = "shutdown")  @Profile("test")  public DataSource datasource() {	  BasicDataSource dataSource = new BasicDataSource();	  dataSource.setUrl("jdbc:h2:tcp://dbserver/~/test");	  dataSource.setDriverClassName("org.h2.Driver");	  dataSource.setUserName("sa");	  dataSource.setPassword("password");	  dataSource.setInitialsize(20);	  dataSource.setMaxActive(30);	  return dataSource;  }  @Bean  @Profile("prod")  public DataSource jndiDataSource() {    JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();    jndiObjectFactoryBean.setJndiName("jdbc/myDS");    jndiObjectFactoryBean.setResourceRef(true);    jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);    return (DataSource) jndiObjectFactoryBean.getObject();  }    // 三种方法都返回了DataSource bean ,仅仅是策略不同而已}

XML中配置profile

datasorce-config.xml

那么问题来了,我们该怎么激活profile呢?

目前我们的项目几乎都是使用:在构建阶段用maven的profile来确定将哪个配置编译到可部署的应用中,缺点在于要为每个环境重新构建应用。

激活profile

Spring在确定哪个profile处于激活状态时,需要依赖两个独立的属性

spring.profile.activespring.profile.default

先判断spring.profile.active是否有值,若没有,再查看spring.profile.default。均没有,就不会激活profile

多种方式来设置这两个属性

1.作为DispactcherServlet参数

2.作为web应用上下文参数

3.作为JNDI条目

4.作为环境变量

5.作为JVM的系统属性

6.在集成测试类中,使用@ActiveProfiles注解设置

具体列子,参考《Spring in action》第4版

转载于:https://my.oschina.net/grittan/blog/3010057

你可能感兴趣的文章
ORA-02292违反完整约束和ORA-02297无法禁用约束条件 cascade禁用主键
查看>>
数据库时间类型和 util 包下时间类型转换
查看>>
Python 之网络编程
查看>>
AtCoder Grand Contest 030题解
查看>>
《JavaScript编程精解》读书笔记目录汇总
查看>>
C++之string类
查看>>
数据结构相关概念
查看>>
BEX5下实现鼠标滚动滚动条
查看>>
SQL Server 2014 BI新特性(一)五个关键点带你了解Excel下的Data Explorer
查看>>
easy_install MySQL-python gcc error
查看>>
为UITextView添加通知..来检测UITextView内容的改变
查看>>
记录一次MySQLWorkBench不能导入导出数据库的问题
查看>>
Java 静态代理和动态代理
查看>>
UVA10881 Piotr's Ants
查看>>
杭电 Problem 3788 ZOJ问题
查看>>
HDU Problem 2141 Can you find it? 【二分】
查看>>
tar打包文件时提示绝对路径的问题
查看>>
设计模式之单例模式
查看>>
memset struct含有string的崩溃
查看>>
时间范围比较
查看>>