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
//DB connection configuration class 
//(don't tell me you're still using xml... ;-)
public class PersistenceConfig {

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

 public LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){
  LocalContainerEntityManagerFactoryBean factoryBean
  = new LocalContainerEntityManagerFactoryBean();
  factoryBean.setDataSource( dataSource() );
  JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){
    // JPA properties
    this.setDatabase( Database.MYSQL);
    this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt..           
  factoryBean.setJpaVendorAdapter( vendorAdapter );
  factoryBean.setJpaProperties( additionalProperties() );

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

I would appreciate comments and improvements.

part 1, part 2 , part 3, part 4

1 comment :