likes
comments
collection
share

springboot配置 spring.profiles.active spring.profiles.include @profile

作者站长头像
站长
· 阅读数 13

springboot配置 spring.profiles.active spring.profiles.include @profile

spring.profiles.active spring.profiles.include

profile的命名方式

application-开头, --横杠(减号)不能少

  • application-{这部分自定义}.properties
  • application-{这部分自定义}.yml
  • application-{这部分自定义}.yaml

springboot配置 spring.profiles.active spring.profiles.include @profile

实例: 比如有个两个配置文件为:

  1. application-freemarker.yml
  2. application-hikari-sqlserver.yml 可以在 application.properties 或 application.yml 或 application.yaml中引入 在application.properties中引入的写法
  • spring.profiles.active=hikari-sqlserver, freemarker
  • spring.profiles.include=hikari-sqlserver, freemarker
  • spring.profiles.active: hikari-sqlserver, freemarker
  • spring.profiles.include: hikari-sqlserver, freemarker

application.properties 等号可以换成冒号空格, 冒号左边不能有空格

在application.yml中引入

spring:
  profiles:
    active: hikari-sqlserver,  freemarker

spring:
  profiles:
    include: hikari-sqlserver,  freemarker

也可写成

spring.profiles.active: hikari-sqlserver, freemarker

spring.profiles.include: hikari-sqlserver,  freemarker

👆上面这种<<冒号空格写法>>既能用于.properties 也能用于.yml .

SpringBoot @Profile

@Profile 可以和 @Bean 一起使用,

@Profile 可以和 @Bean 一起使用, 当配置文件, 例如application.properties等, 添加了下列条目👇

spring.profiles.active: profileName

或着

spring.profiles.include: profileName

加注了@Profile("profileName")@Bean的方法就会在启动时被执行, 当然,类要加@Configuration,甚至@Component就行, 当然,@Bean应该配@Configuration

例如

import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;


@Component

public class ImportProfile {
	
	@Profile("ProfileName")
	@Bean
	public Object beanMethod666() {
		System.out.println("\n\n\n👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇"+
				"""
				\n
				当 active 或 include 了 这个方法上面的 @Profile("ProfileName") 中的 ProfileName (区分大小写)
				这个方法就会被执行
				例如:
				spring.profiles.active= ProfileName

				spring.profiles.include= ProfileName
				控制台就会输出这条信息\n
				"""
				+ "👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆\n\n\n ");
		return "hello";
	}
	
}

springboot配置 spring.profiles.active spring.profiles.include @profile