Spring: Make your java-based configuration more elegant

Spring-Framework-Logo
Hi everyone, I haven’t written new articles a long period of time. A lot of materials were accumulated which need to be posted in my blog in nearest future. But now I want to talk about Spring MVC application configurations. If to be more precisely, I want to talk about java based Spring configurations.

Despite that Spring java based configuration was introduced in 3.0 version, many developers still use XML-based approach. Personally I use annotation based configurations, because they are more convenient in management, in development and in maintenance. If you have read my blog before you could noticed that in all code examples I used exactly java based configurations.

Not so long time ago I have made a code review of one my project. I noticed that something is wrong with a structure of the configurations. Two aspects were bad as for me:

  • All beans were configured in a single class
  • Initialization on web app context was too complex

You can witness these two drawbacks in all my examples of Spring MVC applications. For example you can open one of my last tutorials about Spring REST services with CNVR. Take a look there on two classes: WebAppConfig and Initializer.

WebAppConfig

The first one represents the first point in this article. Definitely I need to do something to split beans configuration logically. To resolve this issue I decided to make two steps:

1) Move DB configurations in a separate class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.mobapp.repository")
public class DataBaseConfig {
        
    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
        
    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    
        @Resource
        private Environment env;
        
        @Bean
        public DataSource dataSource() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                
                dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
                dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
                dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
                dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
                
                return dataSource;
        }
        
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
                LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
                entityManagerFactoryBean.setDataSource(dataSource());
                entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
                entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
                                
                entityManagerFactoryBean.setJpaProperties(hibProperties());
                
                return entityManagerFactoryBean;
        }
        
        private Properties hibProperties() {
                Properties properties = new Properties();
                properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
                properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
                return properties;        
        }
        
        @Bean
        public JpaTransactionManager transactionManager() {
                JpaTransactionManager transactionManager = new JpaTransactionManager();
                transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
                return transactionManager;
        }

}

2) Convert WebAppConfig class in a main configuration class and assign to it the rest of configuration (in current case it would be just DataBaseConfig class) classes via @Import annotation.

@Configuration
@EnableWebMvc
@Import({DataBaseConfig.class})
@ComponentScan("com.mobapp")
@PropertySource("classpath:application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
        
        @Resource
        private Environment env;
        
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        }
        
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer.favorPathExtension(true)
                        .useJaf(false)
                        .ignoreAcceptHeader(true)
                        .mediaType("html", MediaType.TEXT_HTML)
                        .mediaType("json", MediaType.APPLICATION_JSON)
                        .defaultContentType(MediaType.TEXT_HTML);
        }
        
        @Bean
        public ViewResolver contentNegotiatingViewResolver(
                        ContentNegotiationManager manager) {
                
                List< ViewResolver > resolvers = new ArrayList< ViewResolver >();
                
                InternalResourceViewResolver r1 = new InternalResourceViewResolver();
                r1.setPrefix("/WEB-INF/pages/");
                r1.setSuffix(".jsp");
                r1.setViewClass(JstlView.class);
                resolvers.add(r1);
                
                JsonViewResolver r2 = new JsonViewResolver();
                resolvers.add(r2);
                
                ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
                resolver.setViewResolvers(resolvers);
                resolver.setContentNegotiationManager(manager);
         return resolver;
        
        }
        
        /**
        * View resolver for returning JSON in a view-based system. Always returns a
        * {@link MappingJacksonJsonView}.
        */
        public class JsonViewResolver implements ViewResolver {
                public View resolveViewName(String viewName, Locale locale)
                                throws Exception {
                                MappingJacksonJsonView view = new MappingJacksonJsonView();
                                view.setPrettyPrint(true);
                                return view;
                }
        }

}

In this way you can separate single big configuration class in several smaller which will contain specific configs for them.

Initializer

Code of Initializer class is too verbose in the example which I mentioned above and provided the link to it. I registered there the web application root configurations, mapping and filter. How I can decrease a number of code lines? The answer I got looking on AbstractAnnotationConfigDispatcherServletInitializer class. Look on the class and you will notice that it implements WebApplicationInitializer interface, which I have implmented in my previous version of the Initializer class. So here is a new version of the Initializer:

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

        @Override
        protected Class< ? >[] getRootConfigClasses() {
                return null;
        }

        @Override
        protected Class< ? >[] getServletConfigClasses() {
                return new Class< ? >[] { WebAppConfig.class };
        }

        @Override
        protected String[] getServletMappings() {
                return new String[] { "/" };
        }

        @Override
        protected Filter[] getServletFilters() {
                return new Filter[] { new HiddenHttpMethodFilter() };
        }

}

Thank to these two steps I have made my configurations for Spring MVC application more elegant. Now you can do it too. Good luck

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Ajesh Baby

    Your DatabaseConfig file is very interesting. From this inspiration I would like to change my Spring with JSF integration project to Java Config. My project uses Atomikos Transaction Manager and Apache DBCP Data Source for pooling.

    ->Initializer.java

    public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override

    protected Class[] getRootConfigClasses() {

    return null;

    }

    @Override

    protected Class[] getServletConfigClasses() {

    return new Class[] { WebAppConfig.class };

    }

    @Override

    protected String[] getServletMappings() {

    return new String[] { “/”, “/*”, “*.faces”, “*.xhtml” };

    }

    @Override

    public void onStartup(ServletContext servletContext)

    throws ServletException {

    AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();

    //scan the package of your @Configuration java files

    root.scan(“com.shiv.ShivCDB.config”);

    servletContext.addListener(new ContextLoaderListener(root));

    servletContext.addServlet(“Faces Servlet”, “javax.faces.webapp.FacesServlet”);

    servletContext.setInitParameter(“javax.faces.STATE_SAVING_METHOD”, “server”);

    servletContext.setInitParameter(“com.sun.faces.expressionFactory”, “com.sun.el.ExpressionFactoryImpl”);

    servletContext.setInitParameter(“primefaces.PRIVATE_CAPTCHA_KEY”, “6LfwZwoAAAAAAEhRyntKF1PBzysAJLzqp2v-GMRR”);

    servletContext.setInitParameter(“primefaces.PUBLIC_CAPTCHA_KEY”, “6LfwZwoAAAAAAI-oUHpdvRnkMfu9fXQHxc0P7IBu”);

    servletContext.setInitParameter(“javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE”, “true”);

    servletContext.setInitParameter(“primefaces.THEME”, “redmond”);

    servletContext.setInitParameter(“primefaces.SUBMIT”, “partial”);

    super.onStartup(servletContext);

    }

    @Override

    protected Filter[] getServletFilters() {

    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();

    characterEncodingFilter.setEncoding(“UTF-8″);

    OpenEntityManagerInViewFilter openEntityManagerInViewFilter = new OpenEntityManagerInViewFilter();

    openEntityManagerInViewFilter.setPersistenceUnitName(“MySQL”);

    return new Filter[] { characterEncodingFilter, openEntityManagerInViewFilter, new org.primefaces.webapp.filter.FileUploadFilter()};

    }

    }

    ->WebAppConfig.java

    ………………….

    @Bean

    public ViewResolver viewResolver() {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

    viewResolver.setViewClass(JstlView.class);

    viewResolver.setPrefix(“/WEB-INF/jsf”);

    viewResolver.setSuffix(“.jsp”);

    return viewResolver;

    }

    ……………………………………..

    ->DatabaseConfig.java

    @Configuration

    @EnableTransactionManagement

    @ComponentScan(basePackages= “com.shiv.ShivCDB.dao”)

    @PropertySource(value = “classpath:ShivCDB-dao.properties”)

    public class DatabaseConfig {

    @Value(“${MySQL.connection.driver_class}”)

    private String driverClassName;

    @Value(“${MySQL.connection.url}”)

    private String url;

    @Value(“${MySQL.connection.username}”)

    private String username;

    @Value(“${MySQL.connection.password}”)

    private String password;

    @Value(“${MySQL.minPoolSize}”)

    private int maxIdle;

    @Value(“${MySQL.maxPoolSize}”)

    private int maxActive;

    @Value(“${MySQL.dialect}”)

    private String dialect;

    @Value(“${MySQL.show_sql}”)

    private boolean showSql;

    @Value(“${MySQL.generateDdl}”)

    private boolean generateDdl;

    @Bean

    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() {

    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();

    ppc.setLocation(new ClassPathResource(“ShivCDB-dao.properties”));

    ppc.setIgnoreUnresolvablePlaceholders(true);

    return ppc;

    }

    @Bean

    public javax.sql.DataSource dataSource() {

    org.apache.commons.dbcp.BasicDataSource mysqlDs = new org.apache.commons.dbcp.BasicDataSource();

    try {

    mysqlDs.setDriverClassName(driverClassName);

    mysqlDs.setUsername(username);

    mysqlDs.setPassword(password);

    mysqlDs.setUrl(url);

    mysqlDs.setMaxIdle(maxIdle);

    mysqlDs.setMaxActive(maxActive);

    mysqlDs.close();

    } catch (java.sql.SQLException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    return mysqlDs;

    }

    @Bean

    public LocalContainerEntityManagerFactoryBean sessionFactory() {

    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

    factoryBean.setDataSource(dataSource());

    factoryBean.setPersistenceUnitName(“MySQL”);

    factoryBean.setPackagesToScan(“com.shiv.ShivCDB.domain”);

    org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter jpaVendorAdapter = new org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter();

    jpaVendorAdapter.setShowSql(showSql);

    jpaVendorAdapter.setGenerateDdl(generateDdl);

    jpaVendorAdapter.setDatabasePlatform(dialect);

    factoryBean.setJpaVendorAdapter(jpaVendorAdapter);

    factoryBean.setJpaPropertyMap( new java.util.HashMap() {{

    put(“hibernate.transaction.factory_class”, “org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory”);

    put(“hibernate.transaction.manager_lookup_class”, “com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup”);

    put(“hibernate.connection.release_mode”, “on_close”);

    }});

    return factoryBean;

    }

    @SuppressWarnings(“static-access”)

    @Bean

    public JtaTransactionManager jtaTransactionManager() throws javax.transaction.SystemException {

    JtaTransactionManager transactionManager = new JtaTransactionManager();

    com.atomikos.icatch.jta.UserTransactionManager atomikosTransactionManager = new com.atomikos.icatch.jta.UserTransactionManager();

    atomikosTransactionManager.init();

    atomikosTransactionManager.setForceShutdown(true);

    atomikosTransactionManager.setStartupTransactionService(true);

    atomikosTransactionManager.setTransactionTimeout(60);

    atomikosTransactionManager.close();

    com.atomikos.icatch.jta.UserTransactionImp atomikosUserTransaction = new com.atomikos.icatch.jta.UserTransactionImp();

    transactionManager.setTransactionManager(atomikosTransactionManager);

    transactionManager.setUserTransaction(atomikosUserTransaction);

    transactionManager.setTransactionSynchronization(transactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);

    return transactionManager;

    }

    }

    I can’t get more information from web, so I create my own effort. But I can’t connect jtaTransactionManager() with sessionFactory() for provide JTA @Transaction.

    Below mentioned my working xml config code part. Please help me to go with Java Config.