SpringBoot学习1.4-读取配置文件properties和springEL表达式

 

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值