Category Archives: Uncategorized

Using Java class based configuration with Spring

In last few posts about Sring, I have used XML based configuration. But offlate I have figured out that it is easier to use Java based configuration. Here is how it is done for a simple spring mvc application

1. Firstly you will tell web.xml that you will use which class for configuring spring

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.myapp.config.MyConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>

2. You will mark your class with annotation @Configuration

3. For MVC application @EnableWebMvc

4. For component scan- to tell your spring application where to find compoenent @ComponentScan(basePackages = “com.app.my com.app.service com.app.aspect”)

5. If you are using AOP @EnableAspectJAutoProxy

So a sample file would look like

@Configuration
@EnableAspectJAutoProxy
@EnableWebMvc
@ComponentScan(basePackages = "com.app.my com.app.service com.app.aspect")
public class MyConfig extends WebMvcConfigurerAdapter {


	@Bean
	public UrlBasedViewResolver urlBasedViewResolver() {
		UrlBasedViewResolver res = new InternalResourceViewResolver();
		res.setViewClass(JstlView.class);
		res.setPrefix("/WEB-INF/");
		res.setSuffix(".jsp");

		return res;
	}

	@Override
	public void addResourceHandlers(final ResourceHandlerRegistry registry) {

		registry.addResourceHandler("/fonts/**")
				.addResourceLocations("/fonts/").setCachePeriod(31556926);
		registry.addResourceHandler("/css/**").addResourceLocations("/css/")
				.setCachePeriod(31556926);
		registry.addResourceHandler("/images/**")
				.addResourceLocations("/images/").setCachePeriod(31556926);
		registry.addResourceHandler("/js/**").addResourceLocations("/js/")
				.setCachePeriod(31556926);
	}


	@Bean
	public CommonsMultipartResolver multipartResolver() {
		CommonsMultipartResolver mr = new CommonsMultipartResolver();
		mr.setMaxUploadSize(50000000);
		return mr;
	}


}