概述:近期做Spring项目,为了安装灵活性,将环境变量参数写到property配置文件中(例如mysql、hbase配置),在初始化ORM时,使用@Value设置链接参数,但@Value无法获取配置文件中数值,某度、某乎、某dn上的问题解决方案几乎如出一辙,均为复制粘贴,无法解决实际问题。就此情况,翻阅Spring4.x企业应用开发实战,@Value是SPEL在Spring中基于注解配置的方式,在此记录@Value正确使用方法。
一、properties取值方式
1. Spring配置文件中指定配置文件属性,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 1.指定util命名空间 -->
<!-- 2.properties加载配置文件属性-->
<util:properties id="properties" location="classpath:jdbc.properties" />
<!--扫描包-->
<context:component-scan base-package="com.smart.spel"/>
</beans>
2. jdbc.properties配置如下:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbName
userName=root
password=1234
3. @Value初始化bean属性值方式如下:
@Component
public class MyDataSource {
@Value("#{properties['driverClassName']}")//properties对应Spring配置文件util.properties 的id值,类似于js中对象属性取值
private String driverClassName;
@Value("#{properties['url']}")
private String url;
@Value("#{properties['userName']}")
private String userName;
@Value("#{properties['password']}")
private String password;
}
二、属性占位符方式
#{properties['driverClassName']} 写法容易出错,Spring提供一种更简单的写法,仅需要在Spring配置文件中添加property-placeholder ,就可以在表达式中使用${属性}写法。
1. Spring配置文件中添加property-placeholder ,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 1.指定util及context命名空间 -->
<!-- 2.properties加载配置文件属性-->
<util:properties id="properties" location="classpath:jdbc.properties" />
<!-- 3..添加property-placeholder,properties-ref值为--util.properties 的id值>
<context:property-placeholder properties-ref="properties" />
<context:component-scan base-package="com.smart.spel"/>
</beans>
2. @Value 简便表达式用法
@Component
public class MyDataSource {
@Value("#{properties['driverClassName']}")//复杂用法
private String driverClassName;
@Value("${url}")//简单用法
private String url;
@Value("${userName}")
private String userName;
@Value("${password}")
private String password;
}