标签:ati xxx 成员 ${ } autowired path classpath static 读取
1 .系统自带的application.properties (以下代码仅供参考,不能粘贴复制)
假设application.properties文件有下面两个值:
come.test.name = chen
come.test.age = 18
come.test.phone = 18795812345
直接在类中的成员变量上添加注解@Value("${ }"),如下
public class Test(){
@Value("${come.test.name}")
public String name;
@Value("${come.test.age}")
public String age;
@Value("${come.test.phone}")
public String phone;
public static String getProperties(){
String value = "name" + name + "age" + age + "phone" + phone;
return value;
}
}
注意:上面的类Test已经读取加载properties文件,如果你还想在别的类中引用这个Test类。一定在Test类上面加上@Component
@Component
public class Test(){
@Value("${come.test.name}")
public String name;
@Value("${come.test.age}")
public String age;
@Value("${come.test.phone}")
public String phone;
public static String getProperties(){
String value = "name" + name + "age" + age + "phone" + phone;
return value;
}
}
Controller层的类引用Test;
@RestController
public class Demo{
@Autowired
Test test;
public String getPro(){
return test.getProperties();
}
}
2 . 如果你是自定义的properties文件。只需要在Test类加上注解 @PropertySource("classpath:xxx.properties")
@Component
@PropertySource("classpath:xxx.properties")
public class Test(){
@Value("${come.test.name}")
public String name;
@Value("${come.test.age}")
public String age;
@Value("${come.test.phone}")
public String phone;
public static String getProperties(){
String value = "name" + name + "age" + age + "phone" + phone;
return value;
}
}
标签:ati xxx 成员 ${ } autowired path classpath static 读取
原文地址:https://www.cnblogs.com/hope-xu/p/10744634.html