1、注解方式讀取
1-1、@PropertySource配置文件路徑設置,在類上添加注解,如果在默認路徑下可以不添加該注解。
需要用@PropertySource的有:
- 例如非application.properties 主配置文件
- 例如有多配置文件引用,若取兩個配置文件中有相同屬性名的值,則取值為最后一個配置文件中的值
- @PropertySource({"classpath:my/my1.properties","classpath:my/my2.properties"}) public class TestController
- 在application.properties中的文件,直接使用@Value讀取即可,applicarion的讀取優先級最高
2-2、@Value屬性名,在屬性名上添加該注解
@Value("${my.name}")
private String myName;
示例1:使用@Value讀取application.properties里的配置內容
配置文件application.properties
spring.application.name=tn
測試類:
@RestController
//@PropertySource("classpath:my.properties") //application.properties不需要配置注解 默認讀取
public class TaskController {
@Value("${my.name}")
private String userName;
@RequestMapping(value ="/")
public String testDemo() {
System.out.println("userName:" + userName);
return "hello word!";
}
}
結果:
userName:
tn
示例2:使用@Value讀取my.properties里的配置內容
配置文件my.properties
name=tn
測試類:
@RestController
@PropertySource("classpath:my.properties")
public class TaskController {
@Value("${my.name}")
private String userName;
@RequestMapping(value ="/")
public String testDemo() {
System.out.println("userName:" + userName);
return "hello word!";
}
}
結果:
userName:
tn
示例3:static靜態變量使用@Value注入方式
錯誤寫法:Config.getEnv()會返回null
@Component
@PropertySource({ "classpath:my.properties" })
public class MyConfig {
@Value("${name}")
private static String name;
public static String getName() {
return name;
}
public static void setName(String name) {
MyConfig.name= name;
}
}
正確寫法:在非靜態方法setEnv前使用@Value注解
@Component
@PropertySource({ "classpath:my.properties" })
public class MyConfig {
private static String name;
public static String getName() {
return name;
}
@Value("${name}")
public void setName(String name) {
MyConfig.name= name;
}
}
