0.4、Spring源码学习 ——Spring 中的 profile

版权声明:欢迎转载交流,声明出处即可。体能状态先于精神状态,习惯先于决心,聚焦先于喜好 ——Bestcxx https://blog.csdn.net/bestcxx/article/details/91492861

前言

体能状态先于精神状态,习惯先于决心,聚焦先于喜好.

Spring profile 的作用

我们的开发一般会有本地、测试、生产等几个环境,Spring为我们提供了这样的功能,即可以区分不同环境的bean.

给Bean 定义 profile

注解方式
@Component
@Profile("dev")
public class TemServiceImpl implements TemService{
xml配置方式
<beans xmlns="http://www.springframework.org/schema/beans" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
 
    <beans profile="dev">
    	<bean class="com.bestcxx.stu.tem.aspect.serviceimpl.TemServiceImpl" >  </bean>
    </beans>
</beans>
	

激活特定的Profile

启动增加 JVM 参数

-Dspring.profiles.active=dev,其中dev是特定 profile的名字
本方法一般用于本地测试
任何可以设置JVM 启动参数的地方都可以配置,比如TOMCAT、本地环境变量.比如下面 eclipse 启动中的配置

在这里插入图片描述

注解方式激活

在 SpringBoot 中经常存在配置类,可以使用标签激活特定profile
这个方法也适用于本地测试
@ActiveProfiles

@Configuration
@ActiveProfiles(value = {"dev","test"})
public class ActiveMQConfig {

该注解需要 Maven 依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.7.RELEASE</version>
    <scope>test</scope>
</dependency>
web.xml 配置方法

一般区分环境是 web 项目中常见的
在web.xml 中添加以下内容即可激活指定profile

<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>dev</param-value>
</context-param>

Spring profile 不同于Maven profile

Spring 用于自己的Bean 等资源文件加载
Maven 是对自定义资源文件和打包文件对加载
查看 Maven 多版本控制

参考链接

[1]、https://www.liangzl.com/get-article-detail-843.html
[2]、https://www.jianshu.com/p/7ece11832402

猜你喜欢

转载自blog.csdn.net/bestcxx/article/details/91492861