2011-09-14 15 views
5

Estoy usando Spring MVC 3.1.0M2 y estoy tratando de mover mis configuraciones a java beans. Pero me encuentro siguiente error:Spring 3.1: DataSource no se autoconectó a @Configuration class

2011-09-14 18:43:42.301:WARN:/:unavailable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration#0': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: void org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration.setConfigurers(java.util.Collection); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class ru.mystamps.web.config.DbConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean ru.mystamps.web.config.DbConfig.entityManagerFactory()] threw exception; nested exception is java.lang.IllegalArgumentException: DataSource must not be null

Mapeo de web.xml:

<context-param> 
    <param-name>spring.profiles.default</param-name> 
    <param-value>dev</param-value> 
</context-param> 

<servlet> 
    <servlet-name>spring</servlet-name> 
    <servlet-class> 
     org.springframework.web.servlet.DispatcherServlet 
    </servlet-class> 
    <init-param> 
     <param-name>contextClass</param-name> 
     <param-value> 
      org.springframework.web.context.support.AnnotationConfigWebApplicationContext 
     </param-value> 
    </init-param> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      ru.mystamps.web.config.MvcConfig, 
      ru.mystamps.web.config.DbConfig 
     </param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

DbConfig.java:

@Configuration 
@EnableTransactionManagement 
@ImportResource("classpath:spring/datasource.xml") 
public class DbConfig { 

    @Autowired 
    private DataSource dataSource; 

    @Bean 
    public JpaVendorAdapter jpaVendorAdapter() { 
     final HibernateJpaVendorAdapter jpaVendorAdapter = 
      new HibernateJpaVendorAdapter(); 

     jpaVendorAdapter.setDatabasePlatform(dialectClassName); 
     jpaVendorAdapter.setShowSql(showSql); 

     return jpaVendorAdapter; 
    } 

    @Bean 
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
     final LocalContainerEntityManagerFactoryBean entityManagerFactory = 
      new LocalContainerEntityManagerFactoryBean(); 

     entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter()); 
     entityManagerFactory.setDataSource(dataSource); 

     final Map<String, String> jpaProperties = new HashMap<String, String>(); 
     jpaProperties.put("hibernate.format_sql", formatSql); 
     jpaProperties.put("hibernate.connection.charset", "UTF-8"); 
     jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddl); 
     entityManagerFactory.setJpaPropertyMap(jpaProperties); 

     return entityManagerFactory; 
    } 

    @Bean 
    public PlatformTransactionManager transactionManager() { 
     final JpaTransactionManager transactionManager = 
      new JpaTransactionManager(); 

     transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); 

     return transactionManager; 
    } 

    ... 
} 

spring/datasource.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/jdbc 
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd"> 

    <context:property-placeholder location="classpath:spring/database.properties" /> 

    <beans profile="dev"> 
     <bean id="dataSource" 
      class="org.apache.commons.dbcp.BasicDataSource" 
      destroy-method="close"> 
      <property name="driverClassName" value="${db.driverClassName}" /> 
      <property name="url" value="${db.url}" /> 
      <property name="username" value="${db.username}" /> 
      <property name="password" value="${db.password}" /> 
     </bean> 
    </beans> 

    <beans profile="test"> 
     <jdbc:embedded-database id="dataSource" type="HSQL"> 
      <jdbc:script location="classpath:test-data.sql" /> 
     </jdbc:embedded-database> 
    </beans> 

</beans> 

I ex Se creará bean dataSource después de importar datasource.xml, pero siempre recibí este error.

TIA

+0

Tal vez hay algún problema con los perfiles? ¿Has intentado ejecutarlo sin ellos? – axtavt

+0

@axtavt cuando eliminé perfiles y dejé solo 'dataSource' con' jdbc: embedded-database' Tengo el mismo error. –

Respuesta

3

que he encontrado la causa del error, se produce sólo cuando defino manualmente PersistenceAnnotationBeanPostProcessor:

@Bean 
    public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() { 
      // enable injection of EntityManager to beans with @PersistenceContext annotation 
      return new PersistenceAnnotationBeanPostProcessor(); 
    } 

lo siento, porque no he publicado código completo en mi pregunta (porque se supone que este frijol no lo hace importar). Cuando eliminé esta definición, todo funciona como se esperaba. También encontré que en mi caso este bean ya registrado: (comentario cita de org.springframework.orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java)

Note: A default PersistenceAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.

0

Sé que esto no responde a la pregunta real, pero por qué no definir la fuentes de datos utilizando anotaciones así? Tengo una configuración muy similar trabajando sin XML pero no he intentado combinar los dos enfoques.

+0

Lo probé - con clases internas estáticas y con clases separadas - sin éxito, sigue siendo el mismo error. (Si no es una respuesta, ¿por qué no publicarlo como comentario? :)) –

+0

¿Puedes publicar tu intento de configurar las fuentes de datos en el código de Java? –

+0

Ver allí: http://pastebin.ubuntu.com/689938/ También intenté usar clases separadas sin suerte. Un punto cuando funciona: cuando defino solo un 'DataSource' dentro de la clase' DbConfig' (sin perfiles y ninguna clase). –

Cuestiones relacionadas