Spring @Configuration类的问题

eas*_*der 6 configuration spring

我使用带有@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),但$ {minIdle}(类型为int)无法解析!请帮忙.Thanx提前!

dre*_*kka 2

上周我也犯过一些类似的错误。我会检查你使用的是哪个版本的 spring。升级到 3.0.2 后,我在 Validator 类上修复了类似的错误。

我最近还注册了一个数组属性的错误。这似乎确实是您的问题,但您可能需要通过执行属性注入的 spring 代码进行调试,以了解它如何处理您的属性。就我而言,问题出在 BeanDefinitionVistor 中,它包含决定如何处理任何给定属性的代码。追踪这个类。它可能决定不使用属性解析器来注入值。该错误表明情况确实如此,因为它看起来像是试图传递原始字符串,而不是用您传递的值替换它。

祝你好运德里克