springboot(一)映射配置到实体类

  • TestConfig
@Configuration
@ConfigurationProperties(prefix = "com.springboot")
@PropertySource("classpath:test.properties")
public class TestConfig {
    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;
    }
}
  • test.properties
com.springboot.age = 10
  • controller
@RestController
@EnableConfigurationProperties(Student.class)
public class HelloController {

    @Autowired
    private Student student;

    @RequestMapping("hello")
    public String hello() {
        return testConfig.getAge()+"";
    }
}

结果
访问http://localhost:8080/hello
页面会显示10

注解的作用:

  • @ConfigurationProperties(prefix = “student”)

ConfigurationProperties注解除了prefix属性来配置用配置文件中的哪个前缀,还有locations配置具体哪个文件,ignoreUnknownFields = false告诉Spring Boot在有属性不能匹配到声明的域的时候抛出异常

  • @EnableConfigurationProperties(Student.class)

@EnableConfigurationProperties注解告诉Spring Boot 使能支持@ConfigurationProperties,springboot还有其他方法支持@ConfigurationProperties注解,用@Configuration或者 @Component注解, 这样就可以在 component scan时候被发现了

你可能感兴趣的:(springboot,SpringBoot)