If it's really required to access SessionFactory through @Autowire, I'd rather configure another EntityManagerFactory and then use it to configure the SessionFactory bean, like following:
@Configuration
public class SessionFactoryConfig {
@Autowired
DataSource dataSource;
@Autowired
JpaVendorAdapter jpaVendorAdapter;
@Bean
@Primary
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPackagesToScan("com.hibernateLearning");
emf.setPersistenceUnitName("default");
emf.afterPropertiesSet();
return emf.getObject();
}
@Bean
public SessionFactory setSessionFactory(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.unwrap(SessionFactory.class);
} }