SpringAOP 접점 규범 및 획득 방법 파라미터 구현

접점 규범

@Pointcut("execution(* com.example.server.service.TeacherService.*(..))")
위의 절 입 점 은 com.example.server.service.TeacherService 아래 의 모든 방법 에 절 입 됩 니 다.
다음은 절 입 점 표현 식 의 규범 을 상세 하 게 소개 합 니 다.
1.execution():표현 식 주체.
2.첫 번 째 위치:반환 유형 을 나타 내 고*번 호 는 모든 유형 을 나타 낸다.
3.두 번 째 위치:차단 이 필요 한 가방 이름,클래스 이름,방법 명(방법 매개 변수)을 표시 합 니 다.
주의해 야 할 것 은 반드시 모든 종류의 이름 이 어야 한 다 는 것 이다.그 중에서*를 사용 하여 모든 가방 을 표시 할 수 있 습 니 다.
예 를 들 어 com.example.server.service 는 service 가방 의 모든 종 류 를 나타 낸다.com.example.server.는 server 가방 에 있 는 모든 가방 과 모든 종 류 를 표시 합 니 다.
어떤 방법 을 구체 적 으로 지정 할 수도 있 고,이러한 모든 방법 을 표시 할 수도 있다(이전의 반환 유형 을 만족 시 킬 수 있다).
마찬가지 로 매개 변 수 는 구체 적 인 것 일 수 있 습 니 다.예 를 들 어(int,String)도 임의의 매개 변 수 를(..)로 표시 할 수 있 습 니 다.(매개 변수 가 일치 하 는 방법 만 들 어 갈 수 있 습 니 다)
AOP 에서 가 져 오 는 방법 파라미터

"execution(* com.example.server.service.TeacherService.uploadExperience(..)) && args(userId)"
위 표현 식 에 약간의 변경 사항 을 추가 하면 AOP 에서 접근 방법 호출 시의 인 자 를 얻 을 수 있 습 니 다.그러면 AOP 방법 에서 이 인 자 를 사용 할 수 있 습 니 다.
다음은 하나의 예시 이다.

    @After("execution(* com.example.server.service.TeacherService.uploadExperience(..)) && args(userId)")
    public void updateLevel(Long userId){
  //   ,            userId
    }
AOP 세 션 의 인자 가 져 오기
이전에 세 션 에 저 장 된 값 을 AOP 에서 사용 해 야 할 때 도 있 습 니 다.사실 이것 도 매우 간단 하 다.

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
long userId = (long) session.getAttribute(USER_ID);
마찬가지 로 저 희 는 ServletRequestAttributes 를 통 해 request 와 response 를 얻 을 수 있 습 니 다.

HttpServletResponse response = attr.getResponse();
HttpServletRequest request = attr.getRequest();
SpringAOP:절 입 점 주석 을 가 져 오 는 인자
spring op 은 어떻게 절단면 류 에서 절 입 점 관련 방법의 매개 변수,방법 명,반환 값,이상 등 정 보 를 얻 습 니까?
op 사상 은 우리 가 코드 의 결합 을 실현 하 는 데 도움 을 줄 수 있 습 니 다.예 를 들 어 우리 가 전에 언급 한 로그 코드 와 업무 층 코드 를 완전히 독립 시 키 고 spring op 의 대리 류 를 통 해 통합 시 킬 수 있 습 니 다.절단면 류 에서 도 spring 이 제공 하 는 인 터 페 이 스 를 통 해 원 접점 에 관 한 정 보 를 잘 얻 을 수 있 습 니 다.
우선,우 리 는 코드 부터 시작 합 시다.
비 즈 니스 계층 코드 StudentServiceImpl

@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Override
    public int addStudent(Student student) throws Exception {
            System.out.println("addStudent...       ...");
            return 1;
    }
    @Override
    public int deleteStudent(Integer id) throws Exception{
            System.out.println("deleteStudent...       ...");
            int i = 1/0;
            return 0;
    }
}
절단면 류 Student ServiceLogger

@Aspect
@Component
public class StudentServiceLogger {
    @Before("execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )")
    public void doBefore(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+"     ...");
        System.out.println("   :"+ Arrays.asList(args));
    }

    @After("execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )")
    public void doAfter(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+"     ...");
    }

    @AfterReturning(value = "execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )" , returning = "returning")
    public void doReturn(JoinPoint joinPoint,Object returning){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+"    ,    :"+returning);
    }

    @AfterThrowing(value = "execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )",throwing = "ex")
    public void doThrow(JoinPoint joinPoint,Exception ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+"    ,     :"+ex.getMessage());
    }
}
테스트 클래스 AopTest

public class AopTest {
    ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    @Test
    public void test1() throws Exception {
        StudentService studentService = ac.getBean("studentService",StudentService.class);
        studentService.addStudent(new Student());
        System.out.println("================== ===============");
        studentService.deleteStudent(1);
    }
}
마지막 으로 로그 출력 결과 입 니 다.
addStudent 방법 실행 전...
매개 변 수 는:[com.wuwl.domain.Student@7e5c856f]
addStudent...비 즈 니스 계층 코드 실행...
addStudent 방법 실행 후...
addStudent 방법 반환,반환 값:1
=================베 기==================================
deleteStudent 방법 실행 전...
인자:[1]
deleteStudent...비 즈 니스 계층 코드 실행...
deleteStudent 방법 실행 후...
deleteStudent 방법 이상,이상 정보:/by zero
절 입 점 방법 에 관 한 정 보 는 spring 이 org.aspectj.lang.JoinPoint 인터페이스 에 잘 밀봉 되 어 있 습 니 다.여기 서 주의해 야 할 것 은 org.aopaliance.intercept 가방 에 도 이러한 이름 의 인터페이스 가 있 습 니 다.절대 틀 리 지 마 세 요.
joinPoint.getArgs()방법 은 접근 방법의 매개 변수 정 보 를 되 돌려 주 고 값 을 하나의 배열 로 되 돌려 주 며 옮 겨 다 니 면 얻 을 수 있 습 니 다.joinPoint.getSignature()방법의 반환 값 은 방법 으로 서명 하고 서명 인터페이스 에는 방법 명 과 같은 정보 가 포함 되 어 있 습 니 다.
알림 방법 에서 접근 방법의 반환 값 이나 이상 정 보 를 얻 으 려 면 주석 에 대응 하 는 속성 을 사용 해 야 합 니 다.
@AfterReturning 주 해 를 누 르 면 String returning()default"를 볼 수 있 습 니 다.속성,알림 방법 에 반환 값 파 라 메 터 를 추가 한 다음 에 주석 에서 이 파 라 메 터 를 삽입 방법의 반환 값 으로 설명 하면 됩 니 다.조작 방법 은 위의 코드 를 참고 할 수 있 습 니 다.
같은 이치 로@AfterThrowing 주해 의 String throwing()default"을 사용 할 수 있 습 니 다.속성,접근 방법 에 대한 이상 정 보 를 얻 을 수 있 습 니 다.
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기