Skip to main content


100% code based configuration in Spring MVC

If you’re a JEE developer, you must be bored with XML configuration. Thanks to new features of Spring project, now you can have a 100% code based configuration for a web application. Here are some tips:

1.You need a main configuration file





publicclass AppConfig extends WebMvcConfigurerAdapter {


String driverClassName;


public ViewResolver viewResolver() {}


publicstatic PropertySourcesPlaceholderConfigurer propertyConfigurer() {

returnnew PropertySourcesPlaceholderConfigurer();


@Configuration indicates this is a configuration class where beans will be declared.

@ComponentScan configures which directories should be scanned for annotations (like @Service,@Repostory, @Controller etc).

@EnableWebMvc indicates it’s a WebMVC project. For WebMVC project, you need to configure a ViewResolver: InternalResourceViewResolver for JSP/JSTL view technology and ThymeleafViewResolver for Thymeleaf view technology.


2.How to read external property files?

Step 1: You need to define @PropertySource

Step 2: Use @Value and Spring EL, like @Value (“${driverClassName}”)

Step 3: Declare a static PropertySourcesPlaceholderConfigurer bean as above.


3.How to replace traditional web.xml configuration file?

Write a class to implement WebApplicationInitializer interface, then declare mapping and configuration file class as following:

publicclass WebInitializer implements WebApplicationInitializer {

publicvoid onStartup(ServletContext servletContext) throws ServletException {

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();



Dynamic servlet = servletContext.addServlet(“dispatcher”, new DispatcherServlet(ctx));






4.How to exclude static resource files like images, CSS, JS files?

If you dispatch from the root dir like above example, you need to exclude these static files. Just override the addResourceHandlers method of WebMvcConfigurerAdapter interface like this:


publicvoid addResourceHandlers(ResourceHandlerRegistry registry) {





By taking these steps, you don’t need to configure one line of XML!



Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Minjun Wang

More from this Author

Follow Us