0

在 Spring XML 配置中,我有以下内容:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
   ....
</bean>

在 Java 类中,我有 @Autowired private SessionFactory sessionFactory; 没有二传手。这样可行。现在,我将 sessionFactory 更改为 Java 配置,如下所示。

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:jdbc.properties" })
public class PersistenceConfig {

    @Bean
    public SessionFactory sessionFactory() {
    LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(dataSource());
    lsfb.addAnnotatedClasses(...);
            lsfb.setProperties(hibernateProperties());
            return lsfb.buildSessionFactory();
    }
  // ...
}

我收到一个错误“无法自动装配字段”。添加二传手没有帮助。为什么 sessionFactory 不能使用 Java 配置自动装配?

顺便说一句,我也可以通过为 DAO 配置 Java 来解决这个问题。

4

2 回答 2

0

I have added the @ComponentScan annotation and it doesn't solve the problem. The annotation tells Spring to look for any @Components to configure as beans. This problem seems to me is that during the process of creating a bean with @Component, it can't find a bean configured in my Java configuration file which is started in WebAppInitializer.

于 2014-01-28T01:59:04.163 回答
0

我看到你的类上没有@ComponentScan注释@Configuration,所以问题可能在于你如何导入这个配置。请确保所有特定的 bean 都存在于相同的上下文中,或者至少PersistenceConfig是您自动装配 SessionFactory 的上下文的父级

于 2014-01-23T22:33:53.733 回答