Home » Java » Enterprise Java » Spring: Make your java-based configuration more elegant

About Alexey Zvolinskiy

Alexey Zvolinskiy
Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring: Make your java-based configuration more elegant

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.


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
    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";
            private Environment env;
            public DataSource dataSource() {
                    DriverManagerDataSource dataSource = new DriverManagerDataSource();
                    return dataSource;
            public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
                    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
                    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;        
            public JpaTransactionManager transactionManager() {
                    JpaTransactionManager transactionManager = new JpaTransactionManager();
                    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.
    public class WebAppConfig extends WebMvcConfigurerAdapter {
            private Environment env;
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                            .mediaType("html", MediaType.TEXT_HTML)
                            .mediaType("json", MediaType.APPLICATION_JSON)
            public ViewResolver contentNegotiatingViewResolver(
                            ContentNegotiationManager manager) {
                    List< ViewResolver > resolvers = new ArrayList< ViewResolver >();
                    InternalResourceViewResolver r1 = new InternalResourceViewResolver();
                    JsonViewResolver r2 = new JsonViewResolver();
                    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
             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();
                                    return view;

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


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 {

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

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

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

        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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....


Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.