티스토리 뷰
수업 3일차
아래와 같이 수업이 진행이 되어짐
Spring DI (2일차까지 수업한 내용)
Log4j
AOP
Spring은 기본적으로 singleton이다.
Singleton : 시스템 상에서 단 하나의 객체만 생성하여 공유해서 사용하고자 할 때
DI : 결합도↓, 테스트 용이, (spring container가) 의존관계를 주입을 통해 해결
Log4j
AOP
- 공통 관심 사항 정의한 클래스
- 적용 대상 : pointcut
- 적용 시점 : advice
AOP : Aspect Oriented Programming
시스템을 핵심관심사항과 공통관심사항으로 구분하고
공통관심사항을 효율적으로 개발 및 유지보수하기 위해 사용
기존 OOP는 중복된 작업이 불가피 --> AOP로 개선
개발 순서
1. 공통 관심 사항을 정의한 클래스
2. spring aop config xml에서
적용대상 : pointcut
적용시점 : advice
실습 내용
LoggingAspect.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package kosta.common; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.JoinPoint; public class LoggingAspect { private Log log = LogFactory.getLog(getClass()); //JoinPoint : 적용 대상의 정보 public void beforeLogging(JoinPoint point){ // 적용 대상의 인자값을 배열형태로 반환받는다. //추가 요구 사항 0이하일 경우 log.warn("잘못된 입력값"+인자값) 기록 //그렇지 않으면 log.debug() 로 남긴다. Object args[] = point.getArgs(); if(args.length>=1){ int num = (Integer)args[0]; if(num<=0) log.warn("잘못된 데이터..."+num); else{ log.debug("before logging..."+num); } } } } |
AccountService.java
1 2 3 4 5 6 7 8 9 10 11 | package kosta.service; public class AccountService { public void deposit(int money){ System.out.println("입금:"+money); } public void withdraw(int money){ System.out.println("출금:"+money); } } |
CardService.java
1 2 3 4 5 6 7 8 9 10 11 | package kosta.service; public class CardService { public void register(int no){ System.out.println("카드 등록:"+no); } public void sell(){ System.out.println("card sell"); } } |
Test.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package test; import kosta.service.AccountService; import kosta.service.CardService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { /** * kosta.service 이하의 모든 클래스의 메서드들이 * 수행하기 전 , log.debug("before logging"); 이 실행되어야 한다. * * 추가 요구 사항 첫번째 * 넘어온 인자값이 0 이하일 경우 log.warn(data+" 잘못된 입력값"); * * 추가 요구 사항 두번째 * aop 적용하여 logging 시에 대상(target) 클래스명과 메서드명을 함께 로깅 * * aop 로 공통관심사항(before logging)을 효율적으로 처리해보자 * 1. 공통관심사항을 정의 (LoggingAspect class의 beforeLogging() 메서드) * 2. spring 설정 파일에 aop 설정 * ( 적용대상(pointcut) 과 적용시점(advice)을 설정) * @param args */ public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("aop.xml"); CardService card=(CardService)context.getBean("cardService"); AccountService account=(AccountService)context.getBean("accountService"); card.register(1); card.sell(); account.deposit(-100); account.withdraw(200); } } |
aop.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" > <bean id="accountService" class="kosta.service.AccountService"></bean> <bean id="cardService" class="kosta.service.CardService"></bean> <!-- 공통관심사항을 정의한 bean --> <bean id="logging" class="kosta.common.LoggingAspect"></bean> <!-- aop 설정 --> <aop:config> <!-- 1. 적용대상을 지정 model 팩키지이하의 모든 클래스의 모든 메서드가 대상 ( within(kosta.service.*) ) 2. execution() 변경하여 매개변수 타입을 지정 public : 메서드 접근제어자 * : 리턴타입 kosta.service : kosta.service package이하 *Service ; Service로 마치는 클래스 * : 모든 메서드 (int) : 매개변수 int --> <aop:pointcut expression="execution(public * kosta.service.*Service.*(int))" id="beforePointCut"/> <!-- <aop:pointcut expression="within(kosta.service.*)" id="beforePointCut"/> --> <aop:aspect ref="logging"> <!-- 적용시점을 지정:메서드 실행전 --> <aop:before method="beforeLogging" pointcut-ref="beforePointCut"/> </aop:aspect> </aop:config> </beans> |
log4j.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | log4j.rootLogger = warn,stdout log4j.additivity.kosta.common=false log4j.category.kosta.common=debug,stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] - %m%n log4j.appender.dailyfile = org.apache.log4j.DailyRollingFileAppender log4j.appender.dailyfile.File = C:\\java-kosta\\logfile.log log4j.appender.dailyfile.Append = true log4j.appender.dailyfile.DatePattern='.'yyyy-MM-dd log4j.appender.dailyfile.layout = org.apache.log4j.PatternLayout log4j.appender.dailyfile.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] - %m%n |
결과
DEBUG ({main} LoggingAspect.java[beforeLogging]:20) [2013-04-24 22:04:23,516] - before logging...1
카드 등록:1
card sell
WARN ({main} LoggingAspect.java[beforeLogging]:18) [2013-04-24 22:04:23,536] - 잘못된 데이터...-100
입금:-100
DEBUG ({main} LoggingAspect.java[beforeLogging]:20) [2013-04-24 22:04:23,546] - before logging...200
출금:200
'Framework > Spring' 카테고리의 다른 글
[Spring & ibatis] 수업 5일 (0) | 2013.04.26 |
---|---|
[Spring & ibatis] 수업 4일 (0) | 2013.04.25 |
[Spring & ibatis] 수업 2일 (0) | 2013.04.23 |
[Spring & ibatis] 수업 1일 (0) | 2013.04.22 |
[Spring]Spring3.0 MVC에서 폼(Form) 다루기 (0) | 2012.10.08 |