1. XML을 통해 간단한 AOP 구성 살펴보기
1. 먼저 간단한 Student 클래스를 생성합니다
public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println("Age : " + age); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println("Name : " + name); return name; } public void printThrowException() { System.out.println("Exception raised"); throw new IllegalArgumentException(); } }
2. 간단한 AOP 클래스를 생성합니다
public class Logging {/** * This is the method which I would like to execute * before a selected method execution. */public void beforeAdvice() { System.out.println("Going to setup student profile."); } /** * This is the method which I would like to execute * after a selected method execution. */public void afterAdvice() { System.out.println("Student profile has been setup."); } /** * This is the method which I would like to execute * when any method returns. */ public void afterReturningAdvice(Object retVal) { System.out.println("Returning:" + retVal.toString()); } /** * This is the method which I would like to execute * if there is an exception raised. */ public void AfterThrowingAdvice(IllegalArgumentException ex) { System.out.println("There has been an exception: " + ex.toString()); } }
3.SpringAOP.xml 구성
<bean id="student" class="com.seeyon.SpringBean.aop.Student" p:name="yangyu" p:age="27"></bean> <bean id="logging" class="com.seeyon.SpringBean.aop.Logging"></bean> <!--XML方式配置Spring AOP--> <aop:config> <aop:aspect id="log" ref="logging"> 【切面class】 <aop:pointcut id="studentMethod" expression="execution(* com.seeyon.SpringBean.aop.Student.get*(..))"/> 【切点】 <aop:before pointcut-ref="studentMethod" method="beforeAdvice"/> 【方法执行之前触发切面class的beforeAdvice方法】 <aop:after pointcut-ref="studentMethod" method="afterAdvice"/> 【方法执行之后触发切面class的afterAdvice方法】 </aop:aspect> </aop:config>
이 실행을 분석합니다(* com.seeyon.SpringBean.aop.Student.get*(..)) 포인트컷 표현식:
(1) 첫 번째 *는 메소드의 반환 값이 임의적임을 나타냅니다.
(2) get*은 get으로 시작하는 모든 메소드를 나타냅니다.
(3)(.. )은 임의의 숫자를 나타냅니다.
4. 메인 메소드
public class test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("SpringAop.xml"); Student student = (Student) context.getBean("student"); student.getName(); // student.getAge(); // student.printThrowException(); } }
5. 출력 결과
Going to setup student profile. Name : yangyu Student profile has been setup.
2 . Spring AOP 주석 사용.
1. 먼저 간단한 Student 클래스를 만듭니다(.1과 동일, 위 참조).