application.properties中自定义属性的使用

在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;
}

猜你喜欢

转载自www.cnblogs.com/MangogoLee/p/9953505.html
今日推荐