Today we will learn to configure a Spring MVC project ony with annotations and Java classes, in this project we will use the 4.X.X version of Spring, we will also use Maven to handle our dependencies and Tomcat as the container to run our project. I'm also using Eclipse ( Luna version ) as the IDE.

Let's begin creating a Maven project, use the short cut "Alt + Shift + N" and select Maven Project or select the menu File > New > Maven Project. Now on the create project window, select the option "Create a simple project ( skip archetype selection )" and click on "Next". In the next window, we will fill the Group Id with the value "me.efraimgentil", the Artifact Id with "spring-annotation-example" and to finish the Packaging field select "War" and click in "Finish".

With the project created, let's put the necessary dependencies on pom.xml, with those dependencies we will be able to run our Spring MVC project. See the necessary dependencies in the following section:

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.4.RELEASE</version>
</dependency>

With this we can start to configure our Spring MVC configuration with annotations, to start let's create the class SpringConfig on the package "me.efraimgentil.springannotationexample.config", as the following:

package me.efraimgentil.springannotationexample.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"me.efraimgentil.springannotationexample"  })
public class SpringConfig {
  
}

The class will stay empty, at least for this configuration, we are just saying to Spring with packages we want him to scan to identify their components

The next class that we will create is the SpringMvcConfig, put the class in the same package of the previous class. See next:

package me.efraimgentil.springannotationexample.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"me.efraimgentil.springannotationexample.controller"  })
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
  
  @Bean
  public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver
                         = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
  }
  
}

The annotation @EnableWebMvc enables the default configuration of the Spring MVC and register the basic necessary components. Notice the @Bean that we are registering, the InternalResourceViewResolver, we need him so that the Spring finds our JSP pages in the specified path, in this case "/WEB-INF/views/", so don't forget to create the "views" folder inside the directory "WEB-INF". For the same object we also specifies the suffixes that will be considered as views, .jsp in the case.

Now we need to create our initializer, basically he works like a web.xml file, see next how our WebInitializer class will be:

package me.efraimgentil.springannotationexample.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

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

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

}

Our class WebInitializer extends the class AbstractAnnotationConfigDispatcherServletInitializer from Spring, and forces me to implements three methods, the first one "getRootConfigClasses", in this method we will return the classes that contains the Spring configuration with annotations. In the second method "getServletConfigClasses" we return the classes that will make changes in the ServletContex, in the case the class SpringMvcConfig do changes to configure the default dispatcher for Spring. And the last method "getServletMappings" we specify the path that the default spring servlet will responds to, in this case we are specifying the root "/", so all request will pass by my default Spring MVC servlet.

Notice that you can see other configurations that returns null on "getServletConfigClasses" method, and all configuration classes on the "getRootConfigClasses" method, like this will also works without problem ( do the test =D )

With that we have finished our Spring MVC configuration only with annotations , so to test we will create a simple controller in the package "me.efraimgentil.springannotationexample.controller". See next:

package me.efraimgentil.springannotationexample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {
  
  @RequestMapping(value= {"/"} , method = RequestMethod.GET )
  public String hello(){
    return "hello";
  }
  
}

This controller listen to a route to the root ("/") of the application , so this method will be called when we do the request to te URL "http://localhost:8080/spring-annotation-example/", it can be a diferent path depending of your Tomcat configuration. The hello method return an string with the "hello" value, as we did the configuration of the InternalResourceViewResolver, the Spring will search an file with name "hello.jsp" in the folder that we configured in the resolver. In the "/WEB-INF/views/" folder we will create the file "hello.jsp" as following:

webapp
- WEB-INF
- - views
- - - hello.jsp
<!-- Arquivo hello.jsp -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello</title>
</head>
<body>
Hello
</body>
</html>

Now you just need to run your Tomcat server and access the URL to see the result

This is just a basic configuration for Spring with annotations, you can see the sources for this project in: https://github.com/efraimgentil/spring-annotation-example