본문 바로가기
Spring

Spring 4.3.2 자바 annotation 기반 설정

by 수앙 2016. 9. 21.

이클립스 네온으로 스프링 현재 릴리즈 버전인 4.3.3으로 테스트 하려고 했으나

아직 메이븐 레파지토리(http://mvnrepository.com)에 등록이 되어있지 않아 스프링 관련 클래스를 못 찾는 에러가 난다(jar는 다운받아지던데...).

그래서 이전 버전인 4.3.2 버전으로 테스트 한다.

=> 4.3.3으로도 가능하다. 메이븐에 올라왔다.

 

스프링이 xml 기반 설정을 줄이고 annotation 기반 설정으로 가는 추세인 듯 하여

간단하게 설정해보았다.

 

아래 예제는 최소한의 설정만 들어가 있다.

DataSource, Transaction, JSP, UTF-8 등등 설정은 생략하였다.

 

1. web.xml 대신 설정

package com.my.web.common.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ServletInitalizer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ServletConfiguration.class);
        ctx.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

 

2. servlet-context.xml 대신 설정

@Configuration: 자바 기반 설정임을 알려주는 annotation

@EnableWebMvc: xml의 <mvc:annotation-driven>

@ComponentScan: xml의 <context:component-scan>

package com.my.web.common.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.my.web")
public class ServletConfiguration {

}

 

3. 컨트롤러 작성

package com.my.web.home.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {

    private static final Logger logger = LogManager.getLogger();

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map < String, Object > index() {
        logger.info("Welcome to home! Current date and time {}.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        Map < String, Object > map = new LinkedHashMap < > ();
        map.put("id", "test");
        map.put("name", "test");
        map.put("age", 20);
        return map;
    }

}

 

4. pom.xml

...

<properties>
	<org.springframework-version>4.3.2.RELEASE</org.springframework-version>
	<org.aspectj-version>1.8.9</org.aspectj-version>
</properties>

<dependencies>
	<!-- Spring -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${org.springframework-version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${org.springframework-version}</version>
	</dependency>
	<!-- AspectJ -->
	<dependency>
		<groupId>org.aspectj</groupId>
		<artifactId>aspectjrt</artifactId>
		<version>${org.aspectj-version}</version>
	</dependency>
	<!-- Logging -->
	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-api</artifactId>
		<version>2.6.2</version>
	</dependency>
	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-core</artifactId>
		<version>2.6.2</version>
	</dependency>
	<!-- @Inject -->
	<dependency>
		<groupId>javax.inject</groupId>
		<artifactId>javax.inject</artifactId>
		<version>1</version>
	</dependency>
	<!-- Servlet -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.1.0</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet.jsp</groupId>
		<artifactId>javax.servlet.jsp-api</artifactId>
		<version>2.3.1</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<!-- Json -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.8.3</version>
	</dependency>
	<!-- Test -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<artifactId>maven-eclipse-plugin</artifactId>
			<version>2.9</version>
			<configuration>
				<additionalProjectnatures>
					<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
				</additionalProjectnatures>
				<additionalBuildcommands>
					<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
				</additionalBuildcommands>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>true</downloadJavadocs>
			</configuration>
		</plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.5.1</version>
			<configuration>
				<source>1.8</source>
				<target>1.8</target>
				<compilerArgument>-Xlint:all</compilerArgument>
				<showWarnings>true</showWarnings>
				<showDeprecation>true</showDeprecation>
			</configuration>
		</plugin>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>exec-maven-plugin</artifactId>
			<version>1.2.1</version>
			<configuration>
				<mainClass>org.test.int1.Main</mainClass>
			</configuration>
		</plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-war-plugin</artifactId>
			<version>2.4</version>
			<configuration>
				<failOnMissingWebXml>false</failOnMissingWebXml>
			</configuration>
		</plugin>
	</plugins>
</build>

...

 

5. log4j2

로그는 log4j2를 썼다.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="5">
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
		</Console>
	</Appenders>
	<Loggers>
		<Logger name="com.my.web" level="debug"/>
		<Logger name="org.springframework" level="warn"/>
		<Root level="info">
			<AppenderRef ref="Console"/>
		</Root>
	</Loggers>
</Configuration>

 

테스트

요청: http://localhost:8080/

응답: {"id":"test","name":"test","age":20}

 

끝.

'Spring' 카테고리의 다른 글

Spring 4.3.2 log4jdbc-log4j2 설정 방법  (1) 2016.09.29
Springfox 설정  (0) 2016.09.25
Spring batch 예제  (0) 2016.04.20
Spring 4.2.4 + Querydsl 3.7.1  (0) 2016.02.22
Spring WebSocket  (3) 2015.09.13

댓글