likes
comments
collection
share

SpringBoot @Profile

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

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 @Profile

也可以同时匹配多个名称 @Profile({"name1","name2","name3"})

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


@Component
@Profile({"是否支持@符号","启用ImportProfile类","可以使用多个名称", "可以使用@@@@@@符号", "可以支持中文"
	, "类上的@Profile相当于总开关" , "类上的@Profile可以没有"})
public class ImportProfile {
	
	@Profile({"ProfileName", "可以用字符串数组匹配多个", "名称2", "名称3" })
	@Bean
	public Object beanMethod666() {
		System.out.println(
				"""
				\n\n\n👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
				
				当 active 或 include 了 这个方法上面的  ProfileName (区分大小写)
				@Profile({"ProfileName", "可以用字符串数组匹配多个", "名称2", "名称3" })
				中的其中一个名称,	这个方法就会被执行
				例如:
				spring.profiles.active: 启用ImportProfile类

				spring.profiles.include: 可以用字符串数组匹配多个
				控制台就会输出这条信息
				
				👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆\n\n\n 
				""");

		return new ImportProfile(){}; //返回一个匿名内部类意思意思
	}
	
}

中文.properties中会转义显示 SpringBoot @Profile

SpringBoot @Profile

SpringBoot @Profile