'spring java config'에 해당되는 글 1건

  1. 2018.06.09 스프링 자바 설정 기본 세팅 (java config) 1
반응형

최근 필요한 것들을 찾다보면 자바 설정 위주의 예제가 많이 나오더라.
MVC프로젝트에서 자바 설정 세팅에 성공한 방법을 포스팅 해둔다
( 자바설정 : web.xml, servlet-context.xml 등 설정파일을 자바 코드로 관리하는 것 )

1. pom.xml 설정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        <!-- 이것은 기본 세팅값.. 아래의 값으로 변경한다. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
 
        <!-- 이렇게 고친다. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
 
cs

기존에 있던 설정을 고쳐주고, 아래의 내용을 추가한다.


1
2
3
4
5
6
7
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>    
cs

web.xml이 없는것을 문제삼지 않겠다는 설정.


1
2
3
4
5
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.1</version>
</dependency>
cs

아래 자바 설정파일 만들 때 필요한을 사용하기 위해 필요하다.

정확이 어떤 버전인지는 모르겠으나 프로젝트 생성 기본 버전인 3.1.1에서는 추가가 필요하지만

4.2.3버전 정도에서는 추가하지 않고도 어노테이션을 사용할 수 있다.



2. web.xml을 대신할 자바파일 생성

 - 다음은 프로젝트 생성시 기본적으로 생성되는 web.xml에 포함된 아래의 코드를 자바 코드로 변경한다.


* 기본 web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
 
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
    
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
cs

이 코드를.. 아래의 코드로


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class WebInitializer implements WebApplicationInitializer{
 
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {        
        
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.post.javaconfig.configuration");
        
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet"new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        
        
        // 인코딩 필터 적용
        FilterRegistration.Dynamic charaterEncodingFilter = servletContext.addFilter("charaterEncodingFilter"new CharacterEncodingFilter());
        charaterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true"/*");
        charaterEncodingFilter.setInitParameter("encoding""UTF-8");
        charaterEncodingFilter.setInitParameter("forceEncoding""true");
    }    
}
cs

서버 시작시 web.xml이 없으면 WebApplicationInitializer가 구현된 클래스를 알아서 찾아가 세팅을 진행한다.


7번 라인의 설정파일 경로는 설정파일이 모여있을 패키지의 이름을 적어주면 된다.

이렇게 하면 향후에 세팅파일을 만들면 따로 경로추가를 할 필요 없이 알아서 잡아준다.

포스트용 프로젝트의 구조는 아래와 같기에 해당되는 패키지 명을 적어주었다.



그리고 추가적으로, 기본 생성되는 web.xml 파일에는 없지만, 15 - 18번째 줄에 걸쳐 인코딩 필터를 세팅해주었다.



3. servlet-context.xml을 대신할 자바파일 생성

 - 프로젝트 생성시 context.xml 파일이 두개가 자동으로 생성된다. 그 중 root-context에는 아무런 내용이 없기에 패스하고 servlet-context.xml에 들어가 있는 내용을 대신할 자바 파일을 만들어보자.


* 기본 servlet-context.xml

1
2
3
4
5
6
7
8
9
10
<annotation-driven />
 
<resources mapping="/resources/**" location="/resources/" />
 
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
 
<context:component-scan base-package="com.spring.javaconfig" />
cs

이 코드를 자바코드로 변경하면 아래와 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@EnableWebMvc
@ComponentScan("com.post.javaconfig")
public class ServletConfiguration extends WebMvcConfigurerAdapter{
 
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
}
cs

위의 코드와 비교하여 간단하게 설명을 하면


1줄의 @Configuration 은 이 자바 파일이 설정파일이라는 것을 정의하는 어노테이션

2줄의 EnableWebMvc는 xml 파일의 <annotation-driven />

3줄은 따로 설명하지 않는다.


6-7줄은 xml파일의 3번째 줄의 값을 세팅하는 것인데.두 가지 중 한가지만 기록해두었다. 나머지 하나는 아래와 같다.

1
2
3
4
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
cs

두 가지 방법모두 오버라이드 되어 있는데 이를 사용하기 위해서는 WebMvcConfigurerAdapter를 상속해주어야 한다.


11-17줄은 xml파일의 5-8번째 줄에 해당하는 코드이다.




여기까지 세팅을 하고나서 web.xml, root-context.xml, servlet-context.xml 파일을 지우고 서버를 실행하면 정상적으로 실행이 될 것이다.






Posted by NULL..
,