1. 程式人生 > >application.properties中自定義屬性的使用

application.properties中自定義屬性的使用

pat col () ssp 一個 不能 直接 urn st2

在application.properties中寫入如下自定義屬性:

com.mangogo.test1 = "Hello"
com.mangogo.test2 = "World"

使用方法1:直接綁定在屬性上

@RestController
public class Chapter2Test {
@Value(value = "${com.mangogo.test1}")
private String test1 ;
@Value(value = "${com.mangogo.test2}")
private String test2 ;

@RequestMapping("/2")
public
String index(){ return test1+test2; } }

但是這樣使用比較煩,可以直接綁定在類上,使用方法2:

@RestController
public class Chapter2Test {
@Value(value = "${com.mangogo.test1}")
private String test1 ;
@Value(value = "${com.mangogo.test2}")
private String test2 ;

@RequestMapping("/2")
public String index(){
return test1+test2;
}
}

然後註入這個Bean,就可以達到想要的效果。

@RestController
public class Chapter2Controller {
@Autowired
private ConfigBean configBean;

@RequestMapping("/")
public String index(){
return configBean.getTest1()+configBean.getTest2();
}
}

如果有多個properties文件,那麽1.屬性名不能重復,否則會默認讀取第一個properties文件。2.需要用@ProppertySource註解標明文件路徑。

@Getter
@Setter
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix = "com.mangogo2")
@Component
public class ConfigBean {
    private String test1;
    private String test2;
}

application.properties中自定義屬性的使用