Spring/Spring 기본 지식

Spring AOP 설정방법 - @annotation 두 번째(백기선님)

레알윙 2020. 3. 30. 22:41
반응형

1. pom.xml 추가

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

 

2. servelt-context에 설정 추가

<context:annotation-config />
	<context:component-scan base-package="com.victolee.aoptest">
        <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Repository" />
        <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Service" />
        <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Component" />
	</context:component-scan>
<aop:aspectj-autoproxy />

 

3. Controller에서 @anntation 붙이기

@Controller
public class HomeController {
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	@TestAOP
	public String home(Locale locale, Model model) throws Exception {
		System.out.println("메소드 안이여");
		return "home";
	}
}

 

 

4. @annotation interface 만들기

@Retention(RetentionPolicy.CLASS)
@Documented
@Target(ElementType.METHOD)
public @interface TestAOP {
	// @Retention : 애노테이션 정보를 얼마나 유지할 것인가
	// RetentionPolicy.CLASS : 클래스 파일까지 유지할 것이다.
	// RetentionPolicy.SOURCE : 컴파일 하고 나면 사라짐
	// @Target(ElementType.METHOD) : 타겟은 메소드다
	// @Documented : JAVADOC
	
}

 

5. @annotation 구현체 만들기

@Component
@Aspect
public class PerfAspect {

	@SuppressWarnings("unused")
	@Around("@annotation(TestAOP)")
	public Object logPerf(ProceedingJoinPoint pjp) throws Throwable{
		Long begin = System.currentTimeMillis();
		System.out.println("메소드 호출 전이여");
		Object raVal = pjp.proceed();
		System.out.println("메소드 호출 후여");
		return raVal;
	}
}

 

반응형