java Springboot读取properties属性文件的方法有很多,比如:使用Environment、通过@ConfigurationProperties注解、使用PropertiesLoaderUtils等方法,今天我们介绍一种最常用的Springboot读取properties属性文件的方法。
使用@Value注解
例子1:
在application.properties文件中添加属性
my.name=lisi my.old=19
在代码中使用
@RestController @RequestMapping(value = "/my") public class MyController { @Value("${my.name}") private String name; @Value("${my.old}") private int old; @RequestMapping(value = "/test3") public String test3() { return "my name is " + name + "---" + old; } }
例子2:
在application.properties文件中添加属性
com.zyd.type=Springboot - @Value com.zyd.title=使用@Value获取配置文件
程序启动类:Applaction.java
import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class Applaction { @Value("${com.zyd.type}") private String type; @Value("${com.zyd.title}") private String title; /** * * 使用`@Value("${propertyName}")`注解 */ @RequestMapping("/value") public Map<String, Object> value() throws UnsupportedEncodingException { Map<String, Object> map = new HashMap<String, Object>(); map.put("type", type); // *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码 map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8")); return map; } public static void main(String[] args) throws Exception { SpringApplication application = new SpringApplication(Applaction.class); application.run(args); } }
访问结果:
{"title":"使用@Value获取配置文件","type":"Springboot - @Value"}
通过以上内容我们知道了java Springboot读取properties属性文件最常用的方法。感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!