Spring Boot2。在注入@Autowired依赖项之前调用@Bean方法

时间:2018-11-24 10:27:20

标签: spring spring-boot dependency-injection configuration autowired

这只是好奇心。 在下面的示例中,在@Bean entityManager()方法之前注入了@Autowired EntityManagerFactory和@Autowired ApplicationContext。

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private ApplicationContext context;


    @Bean
    public EntityManager entityManager() {

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }

}

但是当我将EntityManager bean类型更改为SessionFactory时,将在自动装配EntityManagerFactory和ApplicationContext bean之前调用sessionFactory()方法,从而在拆开SessionFactory时导致NullPointerException。下面的代码段

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private ApplicationContext context;


    @Bean
    public SessionFactory sessionFactory() {

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager.unwrap(SessionFactory.class);
    }

}

我的问题是:为什么会这样?

2 个答案:

答案 0 :(得分:1)

据我所知,有两种获取SessionFactory的方法:
来自EntityManagerFactory

return entityManagerFactory.unwrap(SessionFactory.class)
//or -> if you have entitymanager
return em.getEntityManagerFactory().unwrap(SessionFactory.class);

从会话中

Session session = entityManager.unwrap(Session.class);
return session.getSessionFactory();


和您说的那样好奇的原因

  在自动装配EntityManagerFactory和ApplicationContext bean导致NullPointerException之前,调用

sessionFactory()方法

情况并非如此

答案 1 :(得分:1)

从Hibernate 5.2开始,SessionFactory也是EntityManagerFactory,因为它现在扩展了所述接口。在此之前,SessionFactory包装了EntityManagerFactory

由于这个原因,EntityManagerFactory无法注入,因为SessionFactory是实现该接口的实际bean。