想要在JAVA Bean中读取配置文件中的内容有两种方式,可以进行获取到
第一种方式:
1、在默认的配置文件application.properties 中进行设置 Key-Value键值对
com.neusoft.duanml=Run SpringBoot
2、在需要使用的JAVA Bean中定义属性,并且注解如下:
@Value("${com.neusoft.duanml}")
private String openSourceName;
3、在JAVA Bean中需要使用的地方进行引用,可以获取到配置值
@RequestMapping("/openSourceName")
public String openSourceName() {
System.out.println(openSourceName);
return openSourceName;
}
第二种方式:
1、任意新建*.properties文件,设置KEY-VALUE键值对 如:resource.properties
com.itzixi.opensource.name=neusoft
com.itzixi.opensource.website=www.neusoft.com
com.itzixi.opensource.language=java
2、编写具体的属性对应JAVA Bean 来封装配置文件*.properties中的属性KEY-VALUE并进行配置如:Resource.java
1 packagecom.leecx.pojo;2
3 importorg.springframework.boot.context.properties.ConfigurationProperties;4 importorg.springframework.context.annotation.Configuration;5 importorg.springframework.context.annotation.PropertySource;6
7 @Configuration8 @ConfigurationProperties(prefix="com.itzixi.opensource")9 @PropertySource(value="classpath:resource.properties")10 public classResource {11
12 privateString name;13
14 privateString website;15
16 privateString language;17
18 publicString getName() {19 returnname;20 }21
22 public voidsetName(String name) {23 this.name =name;24 }25
26 publicString getWebsite() {27 returnwebsite;28 }29
30 public voidsetWebsite(String website) {31 this.website =website;32 }33
34 publicString getLanguage() {35 returnlanguage;36 }37
38 public voidsetLanguage(String language) {39 this.language =language;40 }41
42
43
44 }
其中在JAVA Bean中必须加上 三处注解如下:
@Configuration
@ConfigurationProperties(prefix="com.itzixi.opensource") prefix="com.itzixi.opensource" 为配置文件中的前缀变量值
@PropertySource(value="classpath:resource.properties") 为配置文件在项目的实际位置
注意事项:JAVA Bean中的属性名称 name、website、language必须为配置文件*.properties中@ConfigurationProperties(prefix="com.itzixi.opensource") prefix="com.itzixi.opensource" 去掉前缀的名称
3、在具体的JAVA Bean中使用配置文件的属性值:HelloController.java
1 packagecom.leecx.controller;2
3 importjava.util.Date;4
5 importorg.springframework.beans.BeanUtils;6 importorg.springframework.beans.factory.annotation.Autowired;7 importorg.springframework.beans.factory.annotation.Value;8 importorg.springframework.web.bind.annotation.RequestMapping;9 importorg.springframework.web.bind.annotation.RestController;10
11 importcom.leecx.pojo.LeeJSONResult;12 importcom.leecx.pojo.Resource;13 importcom.leecx.pojo.User;14
15 @RestController16 public classHelloController {17
18 @Autowired19 privateResource resource;20
21 @RequestMapping("/getResource")22 publicLeeJSONResult getResource() {23 System.out.println(resource.getName());24 System.out.println(resource.getWebsite());25 System.out.println(resource.getLanguage());26
27 Resource bean = newResource();28 BeanUtils.copyProperties(resource, bean);29 returnLeeJSONResult.ok(bean);30 }31 }
必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。