Wednesday, July 25, 2012

Spring Profile pattern , part 4

Phase 3: using the pattern

As you can recall, in previous steps we defined an interface for configuration data.
Now we will use the interface in a class which needs different data per environment.

Please note that this example is the key differentiator from the example given in  the Spring blog, since now we don't need to create a class for each profile, since in this case we use the same method across profiles and only the data changes.


Step 3.1 - example for using the pattern
@Configuration
@EnableTransactionManagement
//DB connection configuration class 
//(don't tell me you're still using xml... ;-)
public class PersistenceConfig {

 @Autowired
 private SystemStrings systemStrings; //Spring will wire by active profile

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){
  LocalContainerEntityManagerFactoryBean factoryBean
  = new LocalContainerEntityManagerFactoryBean();
  factoryBean.setDataSource( dataSource() );
  factoryBean.setPersistenceUnitName("my_pu");       
  JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){
   {
    // JPA properties
    this.setDatabase( Database.MYSQL);
this.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
    this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt..           
   
   }
  };       
  factoryBean.setJpaVendorAdapter( vendorAdapter );
  factoryBean.setJpaProperties( additionalProperties() );

  return factoryBean;
 }
//...
@Bean
 public ComboPooledDataSource dataSource(){
  ComboPooledDataSource poolDataSource = new ComboPooledDataSource();
  try {
   poolDataSource.setDriverClass( systemStrings.getDriverClassNameMngHibernate() );
  } catch (PropertyVetoException e) {
   e.printStackTrace();
  }       
                 //is set per environemnt..
  poolDataSource.setJdbcUrl(systemStrings.getJdbcUrl());
  poolDataSource.setUser( systemStrings.getDBUsername() );
  poolDataSource.setPassword( systemStrings.getDBPassword() );
  //.. more properties...       
  return poolDataSource;
 }
}

I would appreciate comments and improvements.
Enjoy!

part 1, part 2 , part 3, part 4

1 comment :