Results 1 to 2 of 2

Thread: @Configuration and SessionFactory

  1. #1
    Join Date
    Nov 2011
    Posts
    1

    Default @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. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,629

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •