我使用带有@Configuration批注的类来配置我的spring应用程序:
@Configuration
public class SpringConfiguration {
@Value("${driver}")
String driver;
@Value("${url}")
String url;
@Value("${minIdle}")
private int minIdle;
// snipp ..
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DataSource dataSource = new DataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setMinIdle(minIdle);
return dataSource;
}
和CLASSPATH中的属性文件
driver=org.postgresql.Driver
url=jdbc:postgresql:servicerepodb
minIdle=1
我想在我的DAO类中获取我的DataSource配置对象:
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfiguration.class);
DataSource dataSource = ctx.getBean(DataSource.class);
但我得到错误:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'springConfiguration': Injection of autowired dependencies
failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private int de.hska.repo.configuration.SpringConfiguration.minIdle; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is **java.lang.NumberFormatException: For input string: "${minIdle}"**
Caused by: java.lang.NumberFormatException: For input string: **"${minIdle}"**
at java.lang.NumberFormatException.forInputString(**Unknown Source**)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
它使用String属性(driver,url),但$ (类型为int)无法解析!请帮忙 . Thanx提前!
3 回答
Updated: 随着更新的信息和您自己的answer,我删除了所有数据源的东西,因为我相信您的问题与
<context:property-placeholder />
元素有关 .您认为answer的错误消息是问题的根源:
我认为问题是
PropertyPlaceholderConfigurer
没有初始化 . 如果使用<context:property-placeholder />
元素对其进行配置,则所有占位符将在初始化过程结束时和Spring容器处于操作阶段之前的后处理操作中使用属性文件中的相应值替换 .如果是解析错误,则属性文件包含如下行:
然后,错误消息将使用
"demo string"
而不是"${minIdle}"
解析时,Spring将使用
@Value
注释处理解析,并且minIdle
字段在我的计算机上正常工作:我设法获取异常消息的唯一方法是忘记添加
<context:property-placeholder />
元素 . 然后我得到了与错误消息中访问的最后一个属性相同的异常消息 .Demo app
一个模拟您的问题的小实验:
没有
property-placeholder
元素:随着
property-placeholder
它的工作就像预期的那样 .我上周遇到了类似的错误 . 我会检查你的 spring 版本 . 转到3.0.2在Validator类上修复了类似的错误 .
我最近还为数组属性注册了一个bug . 这似乎是您的问题,但您可能需要通过执行属性注入的spring代码进行调试,以查看它是如何处理您的属性的 . 在我的例子中,问题出在BeanDefinitionVistor中,其中包含决定如何处理任何给定属性的代码 . 跟踪这个课程 . 可能是它决定不使用属性解析器来注入值 . 错误表明情况就是这样,因为它看起来像是在尝试传递原始字符串,而不是用传递的值替换它 .
祝你好运德里克
我使用Spring 3.0.2 . 而且似乎只能解析String属性 . 我将minIdle属性的类型更改为String:
在我的dataSorce方法中,我将手动String转换为int:
它工作正常(没有强制转换) - 我的应用程序运行这些设置 . 如果我尝试使用我的SpringConfiguartion类作为构造函数参数获取ApplicationContext,则会出错:
完整的Stacktrace
我的xml配置文件: