SpringBoot复习:(22)ConfigurationProperties和@PropertySource配合使用及JSR303校验

一、配置类

package cn.edu.tju.config;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "your")
@PropertySource("classpath:data/01.properties")
public class YourConfig {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

二、data子目录下的01.properties

your.age=32
your.name=Chopin

三、controller中注入配置类:

package cn.edu.tju.controller;


import cn.edu.tju.config.YourConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private YourConfig yourConfig;

    @RequestMapping("/prop")
    public String getProp(){
        return yourConfig.getName() + " " + yourConfig.getAge();
    }
}

注意:
如果application.properties中也有your.age和your.name的配置,它会覆盖@PropertySource注解指定的属性文件中的配置,比如如下application.properties:

server.port=9032
spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx/test
spring.datasource.username=root
spring.datasource.password=My
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
your.age=23
your.name=tju

还可以在@ConfigurationProperties中使用JSR303校验。
1)加依赖

org.springframework.boot
spring-boot-starter-validation

2)在@ConfigurationProperties修饰的类上加@Validated注解,在属性上加校验注解:
SpringBoot复习:(22)ConfigurationProperties和@PropertySource配合使用及JSR303校验_第1张图片

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)