Skip to main content

Development

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

@Configuration

@ComponentScan

@EnableWebMvc

@PropertySource(“classpath:application.properties”)

publicclass AppConfig extends WebMvcConfigurerAdapter {

@Value(“${driverClassName}”)

String driverClassName;

@Bean

public ViewResolver viewResolver() {}

@Bean

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();

ctx.register(AppConfig.class);

ctx.setServletContext(servletContext);

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

servlet.addMapping(“/”);

servlet.setLoadOnStartup(1);

}

}

 

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:

@Override

publicvoid addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler(“/css/**”).addResourceLocations(“/WEB-INF/css/”);

registry.addResourceHandler(“/images/**”).addResourceLocations(“/WEB-INF/images/”);

registry.addResourceHandler(“/js/**”).addResourceLocations(“/WEB-INF/js/”);

}

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

Categories
Follow Us