【SpringBoot】条件装配 @profile

profile

使用说明:

@profile注解的作用是指定类或方法在特定的 Profile 环境生效,任何@Component或@Configuration注解的类都可以使用@Profile注解。
在使用DI来依赖注入的时候,能够根据@profile标明的环境,将注入符合当前运行环境的相应的bean。

使用要求

  1. @Component或@Configuration注解的类可以使用@profile

  2. @Profile中需要指定一个字符串,约定生效的环境

@Profile的使用位置

@Prifile修饰类

DevProfile.java

@Configuration
@Profile("dev")
public class DevProfile {
    private static final Logger log = LoggerFactory.getLogger(DevProfile.class);

    @PostConstruct
    public void init(){
        log.info("-----this profile is dev-----");
    }
}

TestProfile

@Configuration
@Profile("test")
public class TestProfile {
    private static final Logger log = LoggerFactory.getLogger(TestProfile.class);

    @PostConstruct
    public void init(){
        log.info("-----this profile is test-----");
    }
}

通过指定profile的值启动即可;

测试结果

dev

test

@Profile修饰方法

@Configuration
public class TestProfile {
    private static final Logger log = LoggerFactory.getLogger(TestProfile.class);

    @Profile("test")
    @Bean
    public ProfileDto getTest(){
        return new ProfileDto("test");
    }

    @Profile("dev")
    @Bean
    public ProfileDto getDev(){
        return new ProfileDto("dev");
    }
}

PageController.java

@RequestMapping("/")
@RestController
public class PageController {
    
    @Resource
    private ProfileDto profileDto;
    
    @GetMapping("/profileTest")
    public ProfileDto profileTest(){
        return profileDto;
    }
}

测试结果

访问:http://localhost:8082/profileTest

dev

{"env":"dev"}

test

{"env":"test"}

@Profile修饰注解

@Profile注解支持定义在其他注解之上,以创建自定义场景注解。这样就创建了一个@Dev注解,
该注解可以标识bean使用于@Dev这个场景。后续就不再需要使用@Profile("dev")的方式,这样即可以简化代码。

注解 @DevEnv

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface DevEnv {
}

注解 @TestEnv

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface TestEnv {
}
@Configuration
public class TestProfile {
    private static final Logger log = LoggerFactory.getLogger(TestProfile.class);

    @TestEnv
    @Bean
    public ProfileDto getTest() {
        return new ProfileDto("test");
    }

    @DevEnv
    @Bean
    public ProfileDto getDev() {
        return new ProfileDto("dev");
    }
}

测试方法跟结果跟修饰方法一致,不在赘述。

激活 Profile

实际使用中,注解中标示了prod、test、dev等多个环境,
运行时使用哪个profile由spring.profiles.active控制,以下说明2种方式 :配置文件方式、命令行方式。

配置文件方式

application.properties

spring.profiles.active=dev

application.yml

spring:
  profiles:
    active: dev

命令行方式

在打包后运行的时候,添加参数.

java -jar deme-profile-SNAPSHOT.jar   --spring.profiles.active=dev
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章