DEV/SPRING

Rest Service 구현[8]

DEV_KHM 2018. 5. 11. 23:09

전챕터에서 뭔가한가지 문제가있다.


@Override

public STAT addUser(User user) {

// TODO Auto-generated method stub

STAT stat = new STAT();

try {

mapper.addUser(user);

stat.setStat("success");

return stat;

} catch (Exception e) {

stat.setStat("fail");

stat.setCause(e.getMessage());

return stat;

}

}


@Override

public UserList getUserList() {

// TODO Auto-generated method stub

UserList userlist = new UserList();

try {

userlist.setStat("success");

List<User> list=mapper.getUserList();

userlist.setUserList(list);

return userlist;

} catch (Exception e) {

userlist.setStat("fail");

userlist.setCause(e.getMessage());

return userlist;

}

 

 

 

 }


바로 이부문이다 보시다시피 두개다 에러처리가 되어있는데 catch부분이 동일한것을 볼 수 있다 setstat은 어쩔 수 없다고 쳐도

cause는 똑같은 문이 두번이나 반복된다.


이것을 어떻게 처리 할 수 있을까? 스프링은 @ControllerAdvice라는 에러 공통처리하는 부분을 만들어 줄 수 있다.

AnnotationExceptionHandler하나만들어주자 위치는 com.pratice.project에 만들어주자


 package com.pratice.project;


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

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

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


import com.pratice.project.model.STAT;


@RestController

@ControllerAdvice

public class AnnotationExceptionHandler {

@ExceptionHandler(Exception.class)

public STAT handleException(Exception e) {

STAT stat=new STAT();

stat.setStat("fail");

stat.setCause(e.getMessage());

return stat;

}

}


 


내용만봐도 공통적인 사항들을 뺀부분이 보이지않는가?

그리고 자세히보면 맨위에 RestController 애노테이션이 추가되어있는것을 알 수 있다.

이말은 json으로 리턴해주겠다는것이다.


그다음 Impl를 바꾸어주자

 package com.pratice.project.service.impl;


import java.util.List;


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

import org.springframework.stereotype.Service;


import com.pratice.project.dao.IGetDao;

import com.pratice.project.model.Name;

import com.pratice.project.model.STAT;

import com.pratice.project.model.User;

import com.pratice.project.model.UserList;

import com.pratice.project.service.TestService;


@Service

public class TestServiceImpl implements TestService {


@Autowired

private IGetDao mapper;


@Override

public Name getName(String name) {

// TODO Auto-generated method stub

Name Testreturn = mapper.selectName(name);

return Testreturn;

}


@Override

public User getUser(String id) {

// TODO Auto-generated method stub

User user = mapper.selectUser(id);

return user;

}


@Override

public STAT addUser(User user) {

// TODO Auto-generated method stub

STAT stat = new STAT();

mapper.addUser(user);

stat.setStat("success");

return stat;

}


@Override

public UserList getUserList() {

// TODO Auto-generated method stub

UserList userlist = new UserList();

userlist.setStat("success");

List<User> list = mapper.getUserList();

userlist.setUserList(list);

return userlist;


}


}



보면 중복되던 try catch문이 사라진것을 알 수 가 있다.


이제 restclient를 실행해보자.



정상동작하는것을 알 수있다.