1.SpringEL表达式
详情请参考:http://www.cnblogs.com/leiOOlei/p/3543222.html
2.关于Spring中#{}与${}的区别
#{}是SrpingEl表达式的语法规则.
例如:#{bean.属性?:默认值},注意bean.属性必须是要存在的,当为null时匹配
${}是Spring占位符的语法规则,请注意它是否能用,跟bean的初始化时间有关. (参考1, 参考2)
例如:${属性:默认值},如果属性为null或者不存在的话,就是用默认值填充
3.如何将Property文件的属性直接注入到bean类的属性中?
解决办法之一
#先定义properties
username=username
password=123456
<!-- 在Springxml中添加这句 -->
<util:properties id="test" location="classpath:spel/test.properties"/>
<!-- beans的中util的名称空间引入
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd" -->
// 这里是赋值的示例
@Component
public class AnnoProperty {
// @Value("${test.username}")// 注意这样是错误的.$符号不是El表达式的取值方式.
// @Value("#{test.xxx.other}")// 注意这样是错误的,"."这个点不能连续使用.不知道怎么转义
// @Value("#{test.username2?:'默认的username'}") // 注意这样是错误的,如果想使用默认值你需要确保test这类以及username这个属性必须存在
@Value("#{test.username?:'默认的username'}")
private String userName;
@Value("#{test.password}")
private Integer password;
// getter and setter
// ....
}
解决办法之二
#先定义properties
username=username
password=123456
<!-- 这种是Spring占位符的使用方式,也就是${} -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- 可以一次性加载多个资源文件 -->
<value>classpath:spel/test.properties</value>
</list>
</property>
</bean>
<!-- 你可以直接在xml中使用占位符
<bean id="annoProperty" class="com.fong.test.el.anno.AnnoProperty">
<property name="userName" value="${username}"/>
<property name="password" value="${password}"/>
<property name="undefindValue" value="${other.undefindValue}"/>
</bean>-->
<!-- 引入一个问题,可以通过继承PropertyPlaceholderConfigurer的方式来实现配置文件加密/解密 -->
// 你也可直接在注解中使用
@Component
public class AnnoProperty {
// 注意这是占位符方式注入,所以$开头,且没有test这个对象
@Value("${username}")
private String userName;
// @Value("${other.undefindValue}") // 直接使用属性名称输入
// @Value("${xxxxx:other.undefindValue}") // 当xxxxx不存在时,使用other.undefindValue进行赋值
@Value("${xxxxx:123}") // 当xxxxx不存在时,使用other.undefindValue进行赋值
private Integer password;
@Value("${other.undefindValue}")
private String undefindValue;
// getter and setter
// ....
}
如果你参照这种方式还是不能实现的话,可以参考下面是替代方案.
// 这是必须加入到容器,不然没法注入。如果你是xml配置的话就不建议这样麻烦了
@Component
// 申明bean需要使用的resource
@PropertySource("classpath:config.properties")
public class ClazzName{
// 获取resource
@Autowired private Environment environment;
/** 获取config配置文件 */
public String getStr(String key){
return environment.getProperty(key);
}
}
参考地址:
http://sunjun041640.blog.163.com/blog/static/256268322013112325324373/
http://www.myexception.cn/software-architecture-design/428277.html(配置文件加解密)
可能遇到的问题:
https://my.oschina.net/u/1455908/blog/215953
欢迎转载,本文地址:https://my.oschina.net/longfong/blog/800969