1.新建配置文件abc.properties
author.name=yaoge
author.age=888888
author.address=sh1
2.定義AuthorSettings
package com.basic.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ConfigurationProperties(prefix="author")
@PropertySource("classpath:abc.properties")
public class AuthorSettings {
private String name;
private Integer age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3.controller
package com.basic.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* desc:簡單controller
* @date 2017-03-28 11:28:56
* @author 磨練中龍
*
*/
@RestController
@RequestMapping("/simple")
public class SimpleController {
@Autowired
private AuthorSettings authorSettings;
@RequestMapping("/")
public String index(){
return authorSettings.getName()+"--"+authorSettings.getAge()+"--"+authorSettings.getAddress();
}
}
4.啓動項目
/**
* desc:項目啓動入口
* @date 2017-03-28 11:29:39
* @author 磨練中龍
*
*/
@SpringBootApplication
@EnableConfigurationProperties(AuthorSettings.class)
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
八卦下:
@ConfigurationProperties locations過期了,我們可以使用以下註解代替
@PropertySource("classpath:abc.properties")
如果使用application.properties配置文件,可以只使用這個註解,定義好前綴即可,例如:
@ConfigurationProperties(prefix="author")