【问题标题】:PropertySource failing to transform booleanPropertySource 无法转换布尔值
【发布时间】:2014-09-04 08:10:39
【问题描述】:

我有一个 Spring 应用程序,它有一些 XML 配置,可以很好地使用 @Value 从属性文件中连接一个布尔值。我正在将一个单元测试放在一起,使用@Configuration 样式为测试定义配置,而@Value 注释似乎为非字符串类型提供了问题。我查看了文档并发布了信息,但我没有解决这个问题。

堆栈跟踪:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'config': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Boolean vitel.bug.mttp1047.Config.clearDecline; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [cc.manager.clear.decline]
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
  at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
  at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
  at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
  at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
  ... 31 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Boolean vitel.bug.mttp1047.Config.clearDecline; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [cc.manager.clear.decline]
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
  at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
  ... 47 more
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [cc.manager.clear.decline]
  at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:77)
  at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:54)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:877)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
  at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
  ... 49 more
Caused by: java.lang.IllegalArgumentException: Invalid boolean value [cc.manager.clear.decline]
  at org.springframework.beans.propertyeditors.CustomBooleanEditor.setAsText(CustomBooleanEditor.java:122)
  at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:430)
  at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:403)
  at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:181)
  at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:110)
  at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
  ... 53 more

配置:

@Configuration
@PropertySource(value = {"classpath:jdbc.properties", "classpath:bean.properties"})
public class Config {
  @Value("${jdbc.driver}")
  private String jdbcDriver;
  @Value("${jdbc.url}")
  private String jdbcUrl;
  @Value("${jdbc.username}")
  private String jdbcUsername;
  @Value("${jdbc.password}")
  private String jdbcPassword;

  @Value("${cc.manager.clear.decline}")
  private Boolean clearDecline;
  @Value("${cc.manager.agent.schedule.url}")
  private String agentUrl;
  @Value("${cc.manager.reporting.service.url}")
  private String reportingUrl;

  @Bean
  public DataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(jdbcDriver);
    ds.setUrl(jdbcUrl);
    ds.setUsername(jdbcUsername);
    ds.setPassword(jdbcPassword);

    return ds;
  }

  public DeviceDaoHibernateImpl getDeviceDao() throws Exception {
    DeviceDaoHibernateImpl deviceDao = new DeviceDaoHibernateImpl();
    deviceDao.setSf(getSessionFactory());

    return deviceDao;
  }

  public ContactCentreManagerImpl getContactCenter() throws Exception {
    ContactCentreManagerImpl cc = new ContactCentreManagerImpl();
    cc.setDeviceDao(getDeviceDao());
    cc.setClearDecline(clearDecline);
    cc.setAgentScheduleURL(agentUrl);
    cc.setReportingServiceURL(reportingUrl);

      return cc;
  }

  public SessionFactory getSessionFactory() throws Exception {
    Properties props = new Properties();
    props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

    LocalSessionFactoryBean session = new LocalSessionFactoryBean();
    session.setDataSource(getDataSource());
    session.setMappingResources(new String[]{"hibernate_mappings/AsteriskExtension.hbm.xml"});
    session.setHibernateProperties(props);
    session.afterPropertiesSet();

    return session.getObject();
  }
}

beans.properties:

cc.manager.agent.schedule.url=http://vitel/ru80/ScheduleView/NewAgentSchedule.aspx?id=
cc.manager.reporting.service.url=http://vitel/ru80/ReportService.svc/soapAddress
cc.manager.clear.decline=true

任何帮助将不胜感激

【问题讨论】:

  • 您的所有属性都失败了,但您没有看到...添加一个PropertySourcesPlaceholderConfigurer 作为public static @Bean 方法。
  • 这让我明白了。非常感谢

标签: spring configuration spring-el


【解决方案1】:

我只是想改进答案。

解决方案 1:

我们可以使用 PropertySourcesPlaceholderConfigurer

注意:假设您在类路径中有 bean.properties 和 jdbc.properties

1) ApplicationProperties.Java

 public class ApplicationProperties {

            @Bean
            public PropertyPlaceholderConfigurer dbPropertiesConfigurer() {
                PropertyPlaceholderConfigurer configurer = new 
PropertyPlaceholderConfigurer();
                configurer.setLocations(new Resource[] 
                {new ClassPathResource("bean.properties"), 
                 new ClassPathResource("jdbc.properties")});
                configurer.setIgnoreUnresolvablePlaceholders(true);
                return configurer;
            }
        }

2) 实际配置文件

@Configuration
@Import(ApplicationProperties.class)
public class Config {
  @Value("${jdbc.driver}")
  private String jdbcDriver;
  @Value("${jdbc.url}")
  private String jdbcUrl;
  @Value("${jdbc.username}")
  private String jdbcUsername;
  @Value("${jdbc.password}")
  private String jdbcPassword;

  @Value("${cc.manager.clear.decline}")
  private Boolean clearDecline;
  @Value("${cc.manager.agent.schedule.url}")
  private String agentUrl;
  @Value("${cc.manager.reporting.service.url}")
  private String reportingUrl;

<truncated..>

解决方案 2:

使用属性文件值的另一种方法是使用Enviornment

@Configuration
@PropertySource("classpath:jdbc.properties")
public class ApplicationConfiguration {

@Inject
private Environment environment;

  @Bean
  public DataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(environment.getProperty("driver.class.name"));
    ds.setUrl(environment.getProperty("jdbc.url"));
    ds.setUsername(environment.getProperty("username"));
    ds.setPassword(environment.getProperty("password"));

    return ds;
  }

}

【讨论】:

  • 嗨,我面临同样的问题,但是我在 xml 文件中使用 PropertyPlaceholderConfigurer。不知道怎么解决 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多