Configurando Spring com Classes

Após sofrermos bastante com diversas configurações com os famosos arquivos xml podemos fazer as mesmas configurações com anotações em nossas classes.
segue exemplo:

Arquivo SpringConfig.Java

package br.com.codigovivo.config;

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

@Configuration
@ComponentScan(basePackages = {"br.com.codigovivo"})
public class SpringConfig {

}

Arquivo SpringMvcConfig.java

package br.com.codigovivo.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 ={"br.com.codigovivo.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;

}

}

Arquivo de Inicialização do programa WebInitializer.java

package br.com.codigovivo.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() {
// TODO Auto-generated method stub
return new Class[]{SpringMvcConfig.class};
}

@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}

}

Arquivo pom.xml (Maven)

Esse arquivo contém as dependências do projeto.


	4.0.0
	Spring
	Spring
	0.0.1-SNAPSHOT
	war
	
		src
		
			
				maven-war-plugin
				2.4
				
					WebContent
					false
				
			
			
				maven-compiler-plugin
				3.3
				
					1.8
					1.8
				
			
		
	
	
		
			javax.servlet
			javax.servlet-api
			3.1.0
			provided
		

		
			javax.servlet
			jstl
			1.2
		

		
			org.springframework
			spring-webmvc
			4.3.4.RELEASE
		

		
			com.fasterxml.jackson.core
			jackson-databind
			2.6.1
		

		
			org.springframework.data
			spring-data-jpa
			1.10.5.RELEASE
		

		
			com.h2database
			h2
			1.2.125
		

		
			org.hibernate
			hibernate-entitymanager
			5.2.2.Final
		

		
			log4j
			log4j
			1.2.17
		
		
		
			mysql
			mysql-connector-java
			5.1.18
		

	


Related posts

Leave a Comment