[commonConcern.xml]
1 2 3 4 5 6 7 8 9 10 11 12 13 | <bean id="logging" class="spring.chap01.LoggingAspect" /> <!-- ~~ Service 패턴의 이름을 가지고 있는 인터페이스를 구현한 메서드 호출시 --> <aop:config> <aop:pointcut id="servicePointcut" expression="execution(* *..*Service.*(..))" /> <aop:aspect id="loggingAspect" ref="logging"> <aop:around pointcut-ref="servicePointcut" method="logging" /> </aop:aspect> </aop:config> </beans> | cs |
1. ~~Service라는 패턴의 이름을 가진 인터페이스를 구현한 클래스가 '메서드' 호출시 logging이 가로챔을 기억
[MainForAop.java]
1 2 3 4 5 6 7 8 9 10 11 | public static void main(String[] args) { String[] configLocations = new String[] { "applicationContext.xml", "commonConcern.xml" }; // ApplicationContext context = new ClassPathXmlApplicationContext(configLocations); ApplicationContext context = new GenericXmlApplicationContext(configLocations); // 그 전 예제인 BeanFactory보다는 요새 자주 쓰이는 ApplicationContext라는걸 쓴 예제 // 두개의 객체를 ApplicationContext가 객체화한다. WriteArticleService articleService = (WriteArticleService) context.getBean("writeArticleService"); articleService.write(new Article()); } | cs |
배열에 담아 두개의 xml String을 보내도 가능하지만,
GenericXmlApplicationContext가 받는 매개변수 정보에는
1 2 3 4 | public GenericXmlApplicationContext(String... resourceLocations) { load(resourceLocations); refresh(); } | cs |
String... 으로 되어있어서 ( ... 은 여러개의 매개변수를 받을 수 있음.)
ApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml", "commonConcern.xml")
로 함수에 넣어도 상관이없다.
그 전 예제(Main.java)와 똑같이 실행하지만,
이번엔 Aop가 xml내에 존재하기 때문에
~~Service라는 클래스를 구현받은 클래스가 '메서드를 호출'시 Aop가 가로채서
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class LoggingAspect { private Log log = LogFactory.getLog(getClass()); public Object logging(ProceedingJoinPoint joinPoint) throws Throwable{ log.info("기록 시작"); StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); Object retValue = joinPoint.proceed(); return retValue; }catch(Throwable e) { throw e; }finally { stopWatch.stop(); log.info("기록 종료"); log.info(joinPoint.getSignature().getName() + "메서드 실행 시간 : " + stopWatch.getTotalTimeMillis()); } } | cs |
이 클래스를 실행한다.
순서대로
1. Log 객체만들고,
2. log(기록시작)찍고
3. StopWatch 객체 만들고
4. start 찍고
5. proceed()를 실행하는 부분에서 기존에 사용하려다 가로채졌던 write()를 실행한다.
가로챌때에 기존에 사용하려했던 메서드를 자동으로 담아서 오는 기능이 있는 Aop이고,
Object retValue = joinPoint.preceed() 사용하는 메서드로 write 메서드를 실행함을 기억하자.
그 뒤 순서는 똑같이 실행되고 -> catch문이 끝났으니 finally가서 다 실행후. 종료
'JAVA > Spring' 카테고리의 다른 글
Spring 예제 - 어노테이션 , @Aspect (0) | 2018.09.10 |
---|---|
Spring예제 - setter방식 (2) | 2018.09.06 |
Spring예제 - bean컨테이너 사용 (1) | 2018.09.05 |
Spring(maven / gradle) 설치, 순서 (0) | 2018.09.05 |
JsonObject와 JsonArray 사용 (0) | 2018.08.17 |