我使用類@Configuration註釋來配置我的Spring應用程序:問題與Spring @Configuration類
@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類中:
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)
它使用字符串屬性(驅動程序,url),但$ {minIdle}(int類型)無法解析! 請幫忙。感謝提前!
'@ Value'確實可以處理非字符串屬性,並且如果它在這個特定情況下不起作用,那麼奇怪的事情正在發生。 – skaffman 2010-05-16 08:29:39
它可以與字符串屬性一起工作(我的應用程序使用這些設置運行),但不是如果我嘗試獲取ApplicatonContext: ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfiguration.class); – easyrider 2010-05-16 08:47:21