配置profile bean

3.1.@profile注解是spring提供的一个用来标明当前运行环境的注解。

我们正常开发的过程中经常遇到的问题是,开发环境是一套环境,qa测试是一套环境,线上部署又是一套环境。这样从开发到测试再到部署,会对程序中的配置修改多次,尤其是从qa到上线这个环节,让qa的也不敢保证改了哪个配置之后能不能在线上运行。

为了解决上面的问题,我们一般会使用一种方法,就是配置文件,然后通过不同的环境读取不同的配置文件,从而在不同的场景中跑我们的程序。

那么,spring中的@profile注解的作用就体现在这里。在spring使用DI来依赖注入的时候,能够根据当前制定的运行环境来注入相应的bean。最常见的就是使用不同的DataSource了。

下面详细的介绍一下,如何通过spring的@profile注解实现上面的功能。

创建一个Maven项目,其中的配置如下:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.home</groupId>
<artifactId>ProfileTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <name>ProfileTest Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<springframework.version>4.3.7.RELEASE</springframework.version>
</properties>
<dependencies> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies> <build>
<finalName>ProfileTest</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

App:

package com.hom.demo;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; /**
* Hello world!
// */
@Configuration
@ComponentScan(basePackages = {"com.hom.demo"})
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(com.hom.demo.App.class);
Person p = context.getBean(Person.class);
p.speak();
}
}

接口MoveFactor:

package com.hom.demo;
public interface MoveFactor {
void speak();
}

Chines:

package com.hom.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; @Configuration
@Profile(value = "dev")
@Component
public class Chinese implements MoveFactor {
@Override
public void speak() {
System.out.println("我是中国人");
}
}

English:

package com.hom.demo;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; @Component
@Profile("qa")
public class English implements MoveFactor{
@Override
public void speak() {
System.out.println("i am an English");
}
}

German:

package com.hom.demo;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("prod")
public class German implements MoveFactor{
@Override
public void speak() {
System.out.println("i am a German");
}
}

Person:

package com.hom.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Person {
@Autowired
private MoveFactor moveFactor;
public void speak(){
moveFactor.speak();
}
}

SpringTest:

package com.hom.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = App.class)
@ActiveProfiles("dev")
public class SpringTest {
@Autowired
Person p;
@Test
public void testProfile(){
p.speak();
}
}

运行后的结果如下:

当修改@ActiveProfile中的值时,输出的内容也会随之改变。

如果使用的是main函数进行真正的开发、测试和上线时,我们需要设置一下运行参数:

-Dspring.profiles.active=prod

3.2.XML中配置profile

application.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
profile="dev"> <bean id="chinese" class="com.hom.demo.Chinese"></bean> </beans>

我们还可以在<beans>中嵌套定义<beans>元素,而不是为没个环境都创建一个profile.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
>
<beans profile="dev"> <!--这里可以指定需要的profile名-->
<bean id="chinese" class="com.hom.demo.Chinese"></bean>
</beans>
<beans profile="qa">
<bean id="english" class="com.hom.demo.English"></bean>
</beans>
</beans>

3.3.激活profile

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

spring.Profile.active(激活的Profile)

spring.Profile.default(默认的Profile)

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

  • 作为DispathServlet的初始参数
  • 作为Web应用的上下文参数
  • 作为JNDI条目
  • 作为环境变量
  • 作为JVM的系统属性
  • 在集成测试类上,使用@ActiveProfile注解设置

我所喜欢的一种方式是使用DispatcherServlet的参数将spring.rpofiles.default设置开发环境的Profile,我会在Servlet上下文中配置,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" id="WebApp_1525601902125">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLoacation</param-name>
<param-value>application.xml</param-value>
</context-param>
<!--为上下文设置默认的profile-->
<context-param>
<param-name>spring.rpofiles.default</param-name>
<param-value>dev</param-value>
</context-param> <listener>
<listener-class> org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!--为Servlet设置默认的profile-->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.rpofiles.default</param-name>
<param-value>dev</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Spring提供了@ActiveProfile注解设置激活状态

第3章—高级装配—配置profile bean的更多相关文章

  1. Spring高级装配(一) profile

    Spring高级装配要学习的内容包括: Spring profile 条件化的bean声明 自动装配与歧义性 bean的作用域 Spring表达式语言 以上属于高级一点的bean装配技术,如果你没有啥 ...

  2. spring对bean的高级装配之profile机制

    最近在读spring实战一书,个人感觉内容通俗易懂,学到了一些之前并不知道的知识,于是打算在博客里记录一下这些知识点便于后期记忆: 今天要记录的就是spring的条件化创建bean,针对条件化创建be ...

  3. 第3章—高级装配—条件化的Bean

    条件化的Bean 通过活动的profile,我们可以获得不同的Bean.Spring 4提供了一个更通用的基于条件的Bean的创建方式,即使用@Conditional注解. @Conditional根 ...

  4. Spring实战(四)Spring高级装配中的bean profile

    profile的原意为轮廓.剖面等,软件开发中可以译为“配置”. 在3.1版本中,Spring引入了bean profile的功能.要使用profile,首先要将所有不同的bean定义整理到一个或多个 ...

  5. 第3章—高级装配—bean的作用域

    bean的作用域 bean的默认作用域 Spring定义了多种作用域,可以基于这些作用域创建bean,包括: 单例(Singleton):在整个应用中,只创建bean的一个实例. 原型(Prototy ...

  6. 【Spring】高级装配

    前言 前面讲解了bean的核心装配技术,其可应付很多中装配情况,但Spring提供了高级装配技术,以此实现更为高级的bean装配功能. 高级装配 配置profile bean 将所有不同bean定义放 ...

  7. spring学习总结——高级装配学习一(profile与@Conditional)

    前言: 在上一章装配Bean中,我们看到了一些最为核心的bean装配技术.你可能会发现上一章学到的知识有很大的用处.但是,bean装配所涉及的领域并不仅仅局限于上一章 所学习到的内容.Spring提供 ...

  8. Spring高级装配bean

    目录 spring profile 条件化的bean声明 自动装配与歧义性 bean的作用域 Spring表达式语言 一.环境与profile 配置profile  bean 在软件开发的时候,有一个 ...

  9. Spring使用笔记(三) 高级装配

    高级装配 一.环境与Profile 一)配置profile bean 环境的改变导致配置改变(需求:通过环境决定使用哪个bean),可以通过Spring的Profile解决. Profile可以在程序 ...

随机推荐

  1. mongodb spring 集成

    参考文档 mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?op ...

  2. Xcode6制作动态及静态Framework[repost]

    有没有写SDK或者要将一些常用的工具类做成Framework的经历? 你或许自己写脚本完成了这项工作,相信也有很多的人使用 iOS-Universal-Framework ,随着xCode6的发布,相 ...

  3. 微信小程序Wepy框架的三个事件交互($broadcast,$emit,$invoke)

    $broadcast: $broadcast事件是由父组件发起,所有子组件都会收到此广播事件,除非事件被手动取消.事件广播的顺序为广度优先搜索顺序,如上图,如果页面Page_Index发起一个$bro ...

  4. Linux命令行下的vim文本编辑器

    Linux命令行下的vim文本编辑器 下面这个网站的地址讲解的非成分清楚!!!! http://blog.csdn.net/niushuai666/article/details/7275406 学习 ...

  5. 查看WEB ADI所对应的包过程函数

    SELECT BNEINTERFACESBEO.APPLICATION_ID       , BNEINTERFACESBEO.INTERFACE_CODE       , BNEINTERFACES ...

  6. WinRT支持GB2312

    在SL年代,有第三方类库支持 http://encoding4silverlight.codeplex.com 在RT版本有点不兼容,一直没时间看.今天闲的卵疼,就来一段代码兼容一下RT版本,迟点整合 ...

  7. WPF 使用QRCoder生成二维码

    vs中使用Nuget获取QRCoder 窗体中添加按钮和Iage <Window x:Class="QRCoderTest.MainWindow" xmlns="h ...

  8. PHP header函数设置http报文头示例详解以及解决http返回头中content-length与Transfer-Encoding: chunked的问题

    最近在服务器上,多媒体与设备(摄像头)对接的时候,总是发生错误导致设备崩溃,抓包发现响应头不对,没有返回length,使得摄像头立即崩溃.找了一下资料,改了一下响应头就好了. //定义编码 heade ...

  9. WebService-php- 2(17)

    wsdl实例 <?xml version ='1.0' encoding ='UTF-8' ?> <definitions targetNamespace='http://local ...

  10. 【OCP-12c】2019年CUUG OCP 071考试题库(74题)

    74.View the exhibit and examine the structure of ORDERS and CUSTOMERS tables. ORDERS Name     Null?  ...