您的位置:首页 > 编程语言 > Java开发

Spring从配置文件注入变量

2016-03-16 18:33 369 查看


Spring从配置文件注入变量


注入基本数据类型和String,使用@Value注解

使用格式为 : @Value(“${property:default value}”)

当配置文件没有property会设置为默认值,如果有但是没值,会注入null

@Value("${insertVar:1000")
private String insertVar;

@Value("${insertVar:1000}")
private String insertVar;

@Value("#{'${insertVar:1000}'}")
private String insertVar;

@Value("#{config['insertVar']?:'1000'}")
private String insertVar;



配置文件为


insertVar=Strong



注入基本Date类型

两种方式:

使用@Value

@Value("#{new java.text.SimpleDateFormat('yyyy-MM-dd HH:mm:ss').parse('${endTime}')}")
private Date endTime;

上面这种方式不需要修改其他任何配置

使用@DateTimeFormat

@Value("${endTime}")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;

只这样做,不会注入,会报错

需要改配置文件

<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
<mvc:annotation-driven/>

注意bean的id必须为conversionService。换名则失效。

bean在配置文件中未被使用,但是转换格式却生效,期初我也很纳闷,后来看了spring-mvc-xx.xsd的代码,猜测是原因是在annotation-driven中得到调用conversionService
开发中最好是如下这样配置

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService"

class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: