springboot注入配置信息

springboot版本2.1.0.RELEASE

依赖

pom.xml


        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
    

 
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web

        

    

配置文件

application.yml

spring:
  profiles:
    include: test

demo:
  config:
    test: test-demo.yml
    dev: dev-demo.yml
    production: pro-demo.yml

application-test.properties

demo.lee.test=test.demo.properties
demo.lee.dev=dev.demo.properties
demo.lee.production=production.demo.properties

application-dev.properties

test=test.dev.properties
dev=dev.dev.properties
production=production.dev.properties

在springboot中注入使用配置文件中的数据主要有以下三种方式

  1. @Value注解
  2. @ConfigurationProperties注解和@EnableConfigurationProperties注解配合使用
  3. @PropertySource注解

@Value注解

IndexController.class

@RestController
public class IndexController {
    @Value("${demo.lee.test}")
    String test;
    @Value("${demo.config.dev}")
    String dev;

    @RequestMapping("/")
    public String indexController() {
        return test + " " + dev;
    }
}
// 返回test.demo.properties dev-demo.yml

@ConfigurationProperties注解和@EnableConfigurationProperties注解搭配使用

EnvConfig.class

@ConfigurationProperties(prefix = "demo.config")
public class EnvConfig {

    private String test;
    private String dev;
    private String production;
        
  // 注意必须存在setter,否则会注入失败
  /** setter and toString **/
}

IndexController.class

@RestController
public class IndexController {
    @Autowired
    EnvConfig envConfig;

    @RequestMapping("/en")
    public String entityController() {
        return envConfig.toString();
    }

}
// 返回EnvConfig{test='demo.yml', dev='dev-demo.yml', production='pro-demo.yml'}

@PropertySource注解

PropertyConfig.class

@Configuration
@PropertySource("classpath:application-dev.properties")
// 必须指定前缀,否则注入不进来,prefix可以使空字符串,编译器可能会报错
// 但运行不报错
@ConfigurationProperties(prefix = "")
public class PropertyConfig {
    private String test;
    private String dev;
    private String production;

        /** getter、setter和toString **/
}

IndexController.class

@RestController
public class IndexController {
 
    @Autowired
    PropertyConfig propertyConfig;

    @RequestMapping("/pro")
    public String propertyController() {
        return propertyConfig.toString();
    }
}
// 返回PropertyConfig{test='test.dev.properties', dev='dev.dev.properties', production='production.dev.properties'}

你可能感兴趣的:(springboot注入配置信息)