您的位置:首页 > 编程语言 > Java开发

07-SpringBoot——Spring常用配置-Profiles

2017-08-02 07:23 369 查看

Spring常用配置-Profiles

【博文目录>>>】

【项目源码>>>】

【Profiles】

Profile 为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。

(1) 通过设定Environment 的ActiveProfiles 来设定当前context 需要使用的配置环境。在开发中使用@Profile 注解类或者方法,达到在不同情况下选择实例化不同的Bean。
(2) 通过设定jvm 的spring.profiles.active 参数来设置配置环境。
(3) Web 项目设置在Servlet 的context parameter 中。


Servlet 2.5 及以下:



Servlet 3.0 及以上:



【代码实现】

package com.example.spring.framework.profile;

/**
* Author: 王俊超
* Date: 2017-07-11 07:26
* All Rights Reserved !!!
*/
public class DemoBean {
private String content;

public DemoBean(String content) {
super();
this.content = content;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}
}


package com.example.spring.framework.profile;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;

/**
* ① Profile 为dev 时实例化devDemoBean。
* ② Profile 为prod 时实例化prodDemoBean。
* Author: 王俊超
* Date: 2017-07-11 07:26
* All Rights Reserved !!!
*/
public class ProfileConfig {

@Bean
@Profile("dev") //1
public DemoBean devDemoBean() {
return new DemoBean("from development profile");
}

@Bean
@Profile("prod") //2
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}


package com.example.spring.framework.profile;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* Author: 王俊超
* Date: 2017-07-11 07:26
* All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
activeProfiles("dev");
activeProfiles("prod");

}

/**
* ①先将活动的Profile 设置为参数传的值
* ②后直注册Bean 配置类,不然会报Bean 未定义的错误。
* ③刷新容器。
*
* @param profiles
*/
private static void activeProfiles(String... profiles) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();

context.getEnvironment().setActiveProfiles(profiles); //1
context.register(ProfileConfig.class);//2
context.refresh(); //3

DemoBean demoBean = context.getBean(DemoBean.class);

System.out.println(demoBean.getContent());

context.close();
}
}


【运行结果】

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: