首先
一、在resources文件夹下新增自定义example.properties文件
com.example.name=demo
com.example.url=127.0.0.1:8080/demo
二、在Application启动类上添加@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不存在,则采用默认在123
private String projectName;
@RequestMapping("/test")
public String test(){
return "ohh~初步访问!";
}
@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开头的变量
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~初步访问!";
}
@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~初步访问!";
}
@RequestMapping("/test1")
public String test1() {
return environment.getProperty("com.example.name") + "-" + environment.getProperty("com.example.url");
}
}