java - Spring 3.1 : DataSource not autowired to @Configuration class

标签 java spring spring-mvc

我正在使用 Spring MVC 3.1.0M2 并尝试将我的配置移动到 java bean。但是我遇到了以下错误:

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

来自 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>

我希望 bean dataSource 将在导入 datasource.xml 之后创建,但我总是遇到这个错误。

TIA

最佳答案

我已经找到错误的原因,只有当我手动定义PersistenceAnnotationBeanPostProcessor时才会发生:

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

很抱歉,因为我没有在问题中发布完整代码(因为我认为这个 bean 无关紧要)。当我删除这个定义时,一切都按预期进行。我还发现在我的例子中这个 bean 已经被注册了:

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.

(引用来自 org.springframework.orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java 的评论)

关于java - Spring 3.1 : DataSource not autowired to @Configuration class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416024/

相关文章:

java - 使用mockito注入(inject)带有真实参数的bean

java - MockMvc Controller 测试并返回 NullPointerException

用于将 Windows 屏幕镜像到 Anycast 设备的 Java 应用程序

java - 线程和异常处理

java - 写入 stdout,也像真正的终端一样打印提供的输入

Spring 与 Scala 的事务处理

java - 如何在 Java 中向改造请求添加不记名 token

java - 在 Spring 中声明一个显式的对象依赖

Java/J2EE 内部服务器错误

java - 创建类路径资源 [META-INF/spring/app-context.xml] 中定义的名称为 'tilesConfigurer' 的 bean 时出错