Spring Boot实战(二)Spring常用配置 2.4 Profile

2.4.1点睛
Profile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。
(1)通过设定Environment的 ActiveProfiles来设定当前context需要使用的配置环境。在开发中使用@Profile注解类或者方法,达到在不同情况下选择实例化不同的Bean。
(2)通过设定jvm的spring.profiles.active参数来设置配置环境。
(3)Web项目设置在Servlet的context parameter中。
2.4.2演示
(1)示例Bean

package com.wisely.highlight_spring4.ch2.profile;

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;
	}
	

}

(2)Profile配置。

package com.wisely.highlight_spring4.ch2.profile;

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

@Configuration
public class ProfileConfig {
	
	@Bean
	@Profile("dev") //Profile为dev时实例化devDemoBean
	public DemoBean devDemoBean(){
		return new DemoBean("from development profile");
	}
	
	@Bean
	@Profile("prod")	//Profile为prod时实例化prodDemoBean
	public DemoBean prodDemoBean(){
		return new DemoBean("from production profile");
	}
	
}

(3)运行。

package com.wisely.highlight_spring4.ch2.profile;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = 
				new AnnotationConfigApplicationContext();
		context.getEnvironment().setActiveProfiles("prod");//先将活动的Profile设置为prod
		context.register(ProfileConfig.class);//后置注册Bean配置类,不然会报Bean未定义的错误。
		context.refresh(); //刷新容器
		
		DemoBean bean = context.getBean(DemoBean.class);
		System.out.println(bean.getContent());
		
		context.close();
	}
}

结果如图
在这里插入图片描述

将 context.getEnvironment().setActiveProfiles(“prod”);修改为context.getEnvironment().setActiveProfiles(“dev”); 效果如图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值