1.读取配置文件
@PropertySource将指定属性文件的内容加载到spring的上下文中,classpath表示去资源文件夹下寻找该文件。
@Component
@PropertySource({ "classpath:application.properties" })
public class SpringElTest {}
2.读取文件内容,简单spirngEL表达式
注意static变量的获取。
@Component
@PropertySource({ "classpath:application.properties" })
public class SpringElTest {
/**
* 静态变量(如果改变量被静态方法调用,则必须是static的,但是在加载static变量时,配置文件还没加载,改变量是null)
*/
public static String reportInterfFileEncoding;
@Value("${application.reportInterfFileEncoding}")
public void setReportInterfFileEncoding(String reportInterfFileEncoding) {
// 将从配置文件加载的变量赋值给static变量
PbcClassicsDataFileHelper.reportInterfFileEncoding = reportInterfFileEncoding;
}
/**
* 给成员变量赋值:某类的方法返回值
* @Value("#(T(类的全限定名).方法())")
*/
@Value("#{T(System).currentTimeMillis()}")
private Long initTime;
/**
* 给成员变量赋值:属性文件的key对应value
* @Value{"${key}"}
*/
@Value("${server.port}")
private String serverport;
/**
* 给成员变量赋值:其他bean的属性
* @Value{"#{bean的名字.属性}"}
*/
@Value("#{student.grade}")
private int grade;
// 加法
@Value("#{student.grade+1}")
private int grade2;
// 转换为大写,?为判断是否为空
@Value("#{student.englishName?.toUpperCase()}")
private String nameUpper;
// 判断字符串是否相同
@Value("#{student.englishName eq 'echo zhang'}")
private boolean isEcho;
/ 判断字符串为空则给一个默认值
@Value("${student.englishName:默认值}")
private boolean isEcho;
// 文件
@Value("classpath:application.properties")
private Resource testFile;
// 浮点数
@Value("#{3.14f}")
private float pi;
// setters and getters ......
}
其他bean:
@Component
public class Student {
@Value("8")//指定默认值
private int grade;
@Value("echo zhang")
private String englishName;
// setters and getters ......
}
测试:
github:https://github.com/zhangyangfei/springIoC
参考:
https://blog.csdn.net/u011305680/article/details/80271423
https://blog.csdn.net/github_38151745/article/details/83346325