PropertySource не может преобразовать логическое значение

У меня есть приложение 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

Любая помощь будет оценена


person user3465651    schedule 04.09.2014    source источник
comment
Все ваши свойства терпят неудачу, но вы этого не видите... Добавьте PropertySourcesPlaceholderConfigurer как метод public static @Bean.   -  person M. Deinum    schedule 04.09.2014
comment
Это меня устроило. Большое спасибо   -  person user3465651    schedule 04.09.2014


Ответы (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.

Другой способ использовать значения файла свойств — использовать Окружающая среда

@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;
  }

}
person prem    schedule 30.05.2015
comment
привет, у меня такая же проблема, но я использую PropertyPlaceholderConfigurer в XML-файле. Не знаю как решить Спасибо - person Jitendra Vispute; 21.06.2016