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(); } }
【运行结果】
相关文章推荐
- SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active
- Spring Boot教程 - Spring Boot Profiles实现多环境下配置切换
- SpringBoot常用配置 application.yml /application.properties常用配置介绍
- spring-boot-started-logging logback常用配置之<filter>标签详解
- spring boot 学习--07---配置文件处理
- 005-Spring Boot配置分析-配置文件、EnvironmentPostProcessor、Profiles
- SpringBoot之LogBack常用配置
- SpringBoot学习-第二章 常用配置方式-<Spring Boot 实战>
- spring-boot-starter-logging logback常用配置之<appender>标签详解
- SpringBoot常用配置简介
- Spring Boot常用配置
- 05-SpringBoot——Spring常用配置-Spring EL和资源调用
- springboot心得笔记-常用配置
- Common Spring Boot Properties(常用配置)
- spring boot之spring mvc常用配置--@controllerAdvice(5)
- 04-SpringBoot——Spring常用配置-Bean的Scope
- Spring Boot常用注解(三) - 实现Java配置的注解
- SpringBoot(一):Spring常用配置
- spring boot之spring mvc常用配置-静态资源映射(3)
- spring boot 入门 使用spring.profiles.active来分区配置-java编程