spring - PropertySource 无法转换 bool 值

标签 spring configuration spring-el

我有一个 spring 应用程序,它有一些 XML 配置,可以很好地使用 @Value 从属性文件中连接 bool 值。我正在将一个单元测试放在一起,使用@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

任何帮助将不胜感激

最佳答案

我只是想改进答案。

解决方案 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;
  }

}

关于spring - PropertySource 无法转换 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25660372/

相关文章:

java - SPeL 将字符串转换为整数

java - 在 Spring SpEL 中转义 MongoDB 正则表达式字符 - 获取 SpelParseException

java - Spring MVC 和 Hibernate 集成

java - 创建 Spring Bean,其中 class 是字符串?

c++ - 更改我的源代码后,Buildroot 清理我的依赖项

delphi - Delphi 2009 如何转换 Delphi 7 项目重新构建配置

java - Bean 定义被自动配置覆盖

spring - Bootstrap 不适用于 spring-boot?

java - Spring MVC 将对象绑定(bind)解释为字符串

java - 如何消除Spring Java中的类转换异常?