Announcement Announcement Module
Collapse
No announcement yet.
@Configuration and SessionFactory Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Configuration and SessionFactory

    After some digging into the source code I managed to get a working AnnotationSessionFactoryBean bean in my @Configuration class. What bothers me is that I had to explicitly call the afterPropertiesSet method on the factory class to build the object. Without it the factory returns a null object which the transaction manager isn't happy with.

    I would expect Spring to handle this for me, especially since this method throws a checked exception which doesn't feel very Spring-like. Is this the right way to do things or did I miss something in regards to using factories to create beans?

    Code:
    @Configuration
    public class Config {
    
    	@Bean
    	public  DataSource getDataSource() {
    		BasicDataSource dataSource = new BasicDataSource();
    		dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
    		dataSource.setUrl("jdbc:oracle:thin:@192.168.100.100:1521:ORCL");
    		dataSource.setUsername("user");
    		dataSource.setPassword("password");
    		return dataSource;
    	}
    
    	@Bean
    	public SessionFactory getSessionFactory() throws Exception {
    		
    		Properties properties = new Properties();
    		properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
    		properties.put("hibernate.show_sql", "true");
    		
    		AnnotationSessionFactoryBean factory = new AnnotationSessionFactoryBean();
    		factory.setPackagesToScan(new String [] {"my.app.domain"});
    		factory.setDataSource(getDataSource());
    		factory.setHibernateProperties(properties);
    		
    		factory.afterPropertiesSet();
    		return factory.getObject();
    	}
    
    	@Bean(name="transactionManager")
    	public HibernateTransactionManager getTransactionManager() throws Exception  {
    		return new HibernateTransactionManager(getSessionFactory());
    	}
    
    }

  • #2
    The problem with @Configuration is that it doesn't work very nice with factory beans (hence in spring 3.1 there is a new approach to create a session factory for hibernate4). This is mainly because @Bean is sort of a factory bean itself so if you use a factory bean inside that you would have to call the lifecycle methods yourself.

    Comment

    Working...
    X