在 application.properties
写入如下配置内容
my.age=18
my.name=OO
其次定义 MyProperties1.java
文件,用来映射我们在 application.properties
中的内容,这样一来我们就可以通过操作对象的方式来获得配置文件的内容了
package com.battcn.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author Levin
* @since 2018/4/23 0023
*/
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties1 {
private int age;
private String name;
// 省略 get set
@Override
public String toString() {
return "MyProperties1{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
接下来就是定义我们的 PropertiesController
用来注入 MyProperties1
测试我们编写的代码,值得注意的是 Spring4.x
以后,推荐使用构造函数的形式注入属性...
import com.battcn.properties.MyProperties1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Levin
* @since 2018/4/23 0023
*/
@RequestMapping("/properties")
@RestController
public class PropertiesController {
private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);
private final MyProperties1 myProperties1;
@Autowired
public PropertiesController(MyProperties1 myProperties1) {
this.myProperties1 = myProperties1;
}
@GetMapping("/1")
public MyProperties1 myProperties1() {
log.info("=================================================================================================");
log.info(myProperties1.toString());
log.info("=================================================================================================");
return myProperties1;
}
}