1과정을 다맞추었다면


좀더 Rest Service를  멋지게 꾸며보자


많은 분들도 아시겠지만 

Controller단에서 곧바로 로직을 처리하는것보단

인터페이스로 서비스로직을 정리하고 impl패키를 만들어 거기서 서비스 로직을 실행하는것이

좀더 효율적이라고 할 수 있다.


또한 JSON을 처리할때 애노테이션을 붙여서 json의 프로퍼티도 조절 할 수도 있다 .

이번 2과정은 그런과정을 좀더 진행해보자


일단 service 패키지를 하나 만들어주자.



이제 인터페이스를 만들어주자 해당 service에 TestService란 인터페이스를 만들어주자.

인터페이스가 만들어졌다면 아래와 같이 작성해보자.

package com.pratice.project.service;


import com.pratice.project.model.Name;


public interface TestService {

public Name getName(String name);

}


 

정상적으로 만들어졌다면 이제 로직을 실행하는 impl 를 만들어보자

먼저 service패키지안에 impl 패키지 폴더를 하나 만들어주자


패키지 안에 인터페이스를 implements 할 클래스를 만들어주자 이름은 TestServiceImpl로 지정해주자

그리고 해당과 같이 인터페이스 구현부를 작성해주자.

 package com.pratice.project.service.impl;


import com.pratice.project.model.Name;

import com.pratice.project.service.TestService;


@Service

public class TestServiceImpl implements TestService{


@Override

public Name getName(String name) {

// TODO Auto-generated method stub

Name Testreturn = new Name();

Testreturn.setName(name);

return Testreturn;

}


}


 


위의 결과는 1과정에서 실행한 컨트롤러단에 있는 로직을 전부 인터페이스로 옮겨준내용이다.

해당부분으로 로직을 분리해줌으로써 컨트롤러는 로직외적인 부분만 신경쓰고 서비스로직은 인터페이스에서 실행되게 구조를 변경해준것이다. 조금 바뀐 부분이라면 인자값으로 이제 객체를 만들어준다는것이다.


한가지 더 중요한 사실이 있다 서비스 클래스 위를 보면 @Service란 애노테이션이 붙은것을 확인 할 수 있다. 이부분은 bean 객체를 스프링 컨텍스트가 객체로 인식하게끔 만들어준다. 이부분은 컨트롤러 딴에서 객체를 autowired할때 필요하게된다.

이해가 안된다면 스프링에 대해서 조금 공부해보는 시간을 갖는걸 추천한다.



이제 컨트롤러를 바꾸어줘보자.

 package com.pratice.project.controller;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;


import com.pratice.project.model.Name;

import com.pratice.project.service.TestService;


@RestController

public class TestController {


@Autowired

TestService testservice;

@RequestMapping(value = "/test/rest", method = RequestMethod.GET)

public Name getName(HttpServletRequest request, HttpServletResponse response) {

Name rt=testservice.getName("jiwon");

return rt;

}

}



어떤가? 전과 비교해서 훨씬 간편해지지않았나? testservice란 객체는 @Service 애노테이션으로 가지고온 서비스 클래스 그자체이다.

이 서비스 객체 변수를 이용해 간편하게 객체를 리턴시킬수 있다.

이런 나누는결과는 여러가지 개발적으로 로직과 전처리 또는 에러처리등 코드적으로 나누어서 관리를 할 수 있고 디펜던시를 낮출 수 있다.


아여기서 스프링을 공부해 본사람은 알겠지만 설정파일이 가면갈수록 많아질텐데 이런것을 관리하기 위해서

몇가지 수정할 사항이 있다.


기본적으로 /src/webapp/WEB-INF 밑에 스프링에 관련된 설정파일들이 모여있는데 그냥 디폴트로 만들어지는 설정파일은 단일 한개로

지정되어있고 web 설정파일이 있어야할 자리에 Root context와 servlet context가 모여져있어 별로 보기가 좋지않다. 또한 추가적으로 설정파일을 작성한다고 했을시에도 현재는 Root context와 servlet context에만 추가 할수 있기때문에 보기 좋은 구조가아니다.


이런 설정을 바꾸기위해 아래와같이 변경해보자.[/src/webapp/WEB-INF/web.xml]

 <?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


<!-- 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>

  -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath*:spring/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>


</web-app>



보시다시피 root-context.xml를 주석처리하였고 나머지 설정파일들은 spring 폴더에 전부 설정을 할수 있도록 변경하였다.


위와같은설정을하면 resources에 context로 시작하는는 설정파일들을 한곳에서 관리하면서 쉽게 수정할 수 있다.


그럼 실제로 spring폴더를 만들고 common한 설정파일 한개를 만들어줘보자.



spring이 정상적으로 만들어졌다면 이제 이안에 common한 xml를 하나 만들어보자.

파일명은 context-common.xml이다.



 <?xml version="1.0" encoding="UTF-8"?>


<beans

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"

xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">


<context:component-scan use-default-filters="false"

base-package="com.pratice.project">


<context:include-filter expression="org.springframework.stereotype.Component"

type="annotation" />


<context:include-filter expression="org.springframework.stereotype.Service"

type="annotation" />


<context:include-filter expression="org.springframework.stereotype.Repository"

type="annotation" />


</context:component-scan>


</beans>

 


많이 복잡해보이지만 전혀그렇지않다 상단 내용은 spring기능을 사용하기 위한 선언문이고

아래 내용은 전체 패키지내에서  Componet,Service,Repository로 들어오는 애노테이션은 빈처리로 스캔하겠다는 의미다 

빈처리는 객체로 인식하겠다는소리다.


또한 추가적으로 src/webpp/WEB_INF/spring/appServlet/serlet-context.xml를 아래와 같이 바꾸어준다.

 <?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:beans="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->

<annotation-driven />


<context:component-scan base-package="com.pratice.project" use-default-filters="false">

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />

</context:component-scan>

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->

<resources mapping="/resources/**" location="/resources/" />


<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

<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.pratice.project">


</context:component-scan>

 -->

</beans:beans>


 

여러 내용이 많지만 간단하게 말해 컨트롤러 애노테이션을 스캔해서 객체화 시키겠다는것이다.


이렇게 나누어 두는 내용은 view단에 서블릿에서만 컨트롤러 단에 해당되거나 뷰단에 해당되는 내용들을 처리하고

나머지 설정이나 서비스단이나 다른 애노테이션처리는 전부 다른 설정파일에서 처리하겠다는 의미다.


이렇게 나누는 이유는 크게 2가지로 압축된다


첫째. 스프링에서 뷰단,컨트롤러 설정은 서블릿 컨텍스트가 담당하고 나머지 설정파일들은 전부 다른 컨텍스트가 담당하게 만드는게 관리하기 편한다.

두번째. web.xml 에서 보면 context-*.xml로 선언되있는것을 볼수가있다. 즉  context 이름으로 다양한 설정파일을 쉽게 관리 할수 있다.


이런점때문에 나누었고 결론적으로 서비스 bean[@Service]을 관리하는건 common context가 관리하고 나머지 @Controller 나 jsp 매핑은 서블릿 context가 관리 하는것이다.


다음 3장에서는 DAO를 통한 데이터베이스에 해당정보를 가지고와서 뿌려주는 것을 배워보도록하겠다.



'DEV > SPRING' 카테고리의 다른 글

Rest Service 구현[5]  (0) 2018.05.11
Rest Service 구현[4]  (0) 2018.05.11
Rest Service 구현[3]  (0) 2018.05.11
Rest Service 구현[1]  (0) 2018.05.11
Spring restful service 참고사이트  (0) 2018.05.11

+ Recent posts