2020년 2월 18일 화요일

[spring] aop 설정하기

많은 글들에서 보아와서 알겟지만. 간단하게 정리하면
aop = 메소드 껴넣기 라 정리 할수 있겟다.

구현코드

root-context.xml 에 AuthorizationAspect, ClientDeviceAspect  를 정의한다.

AuthorizationAspect  = 특정 유저 타입체크 하여 비지니스 로직 처리

<!-- AOP 설정 -->
root-context.xml
...

<bean id="companyAspect" class="패키지경로.AuthorizationAspect"/>

...


//위에 root-context.xml class 경로에 AuthorizationAspect  파일을 생성한다.


@Aspect
public class AuthorizationAspect {

    // @CheckUser 가 붙은 메소드 실행 직전에 실행됨 @annotation(target) 을통해
    // 에노테이션 설정값을 가져올수 있음
    // @Before : 타겟 메서드 실행전
    // @After : 타겟 메서드 실행후
    // @Around : 타겟 메서드 실행 전후
    // @AfterReturning : 타겟 메서드 완료후 무조건
    // @AfterThrowing : 타겟 메서드에서 예외 발생시.



//com.alan.spring.aop.annotations.CheckUser 인터페이스 작성

// 커스텀 에노테이션 설정 
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CheckUser {
int[] checkUser();  //숫자 배열을 에노테이션 인자값으로 받을수 있음
}





    @Before("@annotation(com.alan.spring.aop.annotations.CheckUser) &&  @annotation(target)")
    public void checkUser(JoinPoint jp, CheckUser target) throws Exception {

        //메서드에 인자 값을 가져올수 있음
    Object arg[] = jp.getArgs();

        //첫번째 파라미터 HttpServletRequest 를 가져온다
        //파라미터 순서 안맞을시 오류가 남.
        //
    HttpServletRequest req = (HttpServletRequest)arg[0];
        //아래 방식으로 대체 가능  
        //HttpServletRequest req = ((ServletRequestAttributes)                                              //RequestContextHolder.getRequestAttributes()).getRequest();

        //현제 메서드를 실행하는 주체의 세션정보
        AccountVo session = (AccountVo)req.getAttribute("user");
        
                
        //에노테이션에 정의된 권한 리스트
        int[] list = target.checkUser();


        if(StringUtils.isEmpty(list)) {
        throw new MyBusinessException("",Constant.ERROR_404);
        }
        boolean result = false;
        loop: for(int i = 0; i < list.length; i++) {
                //유저의 타입이 메서드의 정의된 권한리스트에 존재할경우 result에 true
        if(session.getAccountTypeId() == list[i]) {
        result = true;
        break loop;
        }
        }
        if(!result) {
        throw new MyBusinessException("",Constant.ERROR_404);
        }
    }
    
 }   


//적용 메서드 (Constant.ACCOUNT_TYPE_SYSUSER 는 상수 값)
@CheckUser(checkUser = {Constant.ACCOUNT_TYPE_SYSUSER})
@Override
public HashMap<String, Object> getClientPostionInfoByCompanyIdTms(HttpServletRequest req, Locale locale,
ClientVo clientVo) throws Exception {
......
}


주의사항

스프링웹 에서 일종의 미들웨어 처리 우선순위는 다음과 같다.

servlet Filter > spring interceptor > aop












댓글 없음:

댓글 쓰기

[lunux]리눅스 폴더별 용량 확인

리눅스 폴더별 용량 확인 조회 하고자 하는 디렉토리 리스트가있는 경로로 이동후 du -h --max-depth=1