首先
一年堆、在resources文件夾下新增自定義example.properties文件
com.example.name=demo
com.example.url=127.0.0.1:8080/demo
二斑匪、在Application啟動(dòng)類上添加@PropertySource注解
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource(value = {"example.properties"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
1. 基于@Value注解讀取
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${com.example.name:123}") //如果com.example.name不存在,則采用默認(rèn)在123
private String projectName;
@RequestMapping("/test")
public String test(){
return "ohh~初步訪問(wèn)!";
}
@RequestMapping("/test1")
public String test1(){
return projectName;
}
}
2.基于@ConfigurationProperties注解讀取
一.新建PropertiesConfig類
package com.example.demo.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data //使用需要新增lombok maven配置
@Component
@ConfigurationProperties(prefix = "com.example") //讀取以com.example開(kāi)頭的變量
public class PropertiesConfig {
private String name;
private String url;
}
二.使用方式
package com.example.demo.controller;
import com.example.demo.config.PropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
PropertiesConfig propertiesConfig;
@RequestMapping("/test")
public String test(){
return "ohh~初步訪問(wèn)!";
}
@RequestMapping("/test1")
public String test1(){
return propertiesConfig.getName()+"-"+propertiesConfig.getUrl();
}
}
3.基于Environment方式讀取
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
Environment environment;
@RequestMapping("/test")
public String test() {
return "ohh~初步訪問(wèn)!";
}
@RequestMapping("/test1")
public String test1() {
return environment.getProperty("com.example.name") + "-" + environment.getProperty("com.example.url");
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者