简体   繁体   中英

Can't Autowire SessionFactory with Java Configuration

The configuration class name is marked in yellow color and it says Application context not configured for this file

My Config Class :

@Configuration
@EnableTransactionManagement
public class DatabaseConfig {

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan("com.tornikeshelia.model");
    sessionFactory.setHibernateProperties(getHibernateProperties());
    return sessionFactory;
}

private Properties getHibernateProperties(){
    Properties prop = new Properties();
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL57InnoDBDialect");
    return properties;
}

@Bean(name = "dataSource")
public BasicDataSource dataSource(){
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.cj.jdbc.Driver");

    ds.setUrl("jdbc:mysql://localhost:3306/test?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf-8");
    ds.setUsername("username");
    //ds.setPassword("");

    return ds;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory);
    return txManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
    return new PersistenceExceptionTranslationPostProcessor();
}
}

I've commented out ds.setPassword because my test database doesn't have any password protection. Also the hibernate doesn't auto create tables from my Entity class , I think thats because of this configuration file not being read by Spring

When trying to autowire SessionFactor in my DaoImpl class via :

@Resource(name = "sessionFactory")
private SessionFactory session;

The error says Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.tornikeshelia.dao.PersonDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.tornikeshelia.dao.PersonDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

SOLUTION : The problem was 1)The location of config package and 2) in the warning message that was on the class name (yellowed out with message - Application context not configured for this file So if anybody has same problem here's the solution -

1) move your config package inside the parent package where the model package is

2) Step on the class name (click anywhere on the class name) the yellow light bulb will appear, click on it and then click on configure application context , a new tab will appear where you should choose this class and press okay .

Try to edit your config class and update the transationManager() bean :

    @Bean
    public HibernateTransactionManager transactionManager(){
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

Your error may occur because you try to inject a bean that has not bean created yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM