SSH 프레임 워 크 시리즈: Spring AOP 응용 기록 로그 데모
Spring 의 AOP 는 Aspect Oriented Programming 의 줄 임 말로 절단면 프로 그래 밍 을 위 한 사전 컴 파일 방식 과 런 타임 동적 대 리 를 통 해 프로그램 기능 의 통일 적 인 유 지 를 실현 하 는 기술 입 니 다.다음은 Spring AOP 의 작은 예 입 니 다.
원본 코드:https://github.com/nuptboyzhb/SpringAOPDemo
2. 예 소개
2.1 절단면 aspect: Logging. java
/*
* $filename: Logging.java,v $
* $Date: 2013-12-10 $
* Copyright (C) ZhengHaibo, Inc. All rights reserved.
* This software is Made by Zhenghaibo.
*/
package edu.njupt.zhb;
/*
*@author: ZhengHaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: [email protected]
*2013-12-10 Nanjing,njupt,China
*/
public class Logging {
public void beforeAdvice(){
System.out.println("Logging:before... ");
}
public void afterAdvice(){
System.out.println("Logging:after... ");
}
/**
*
* @param retVal
*/
public void afterReturningAdvice(Object retVal){
if(retVal==null){
return;
}
System.out.println("Logging:return :"+retVal.toString());
}
public void afterThrowingAdvice(IllegalArgumentException ex){
System.out.println("Logging:exception:"+ex.toString());
}
}
2.2Bean: Student.java
/*
* $filename: Student.java,v $
* $Date: 2013-12-10 $
* Copyright (C) ZhengHaibo, Inc. All rights reserved.
* This software is Made by Zhenghaibo.
*/
package edu.njupt.zhb;
/*
*@author: ZhengHaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: [email protected]
*2013-12-10 Nanjing,njupt,China
*/
public class Student {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printThrowException(){
System.out.println("Exception in Student.class...");
throw new IllegalArgumentException("Exception from Student...");
}
public void print(String say){
System.out.println("Say:"+say+",Name = "+name);
}
}
2.3xml 파일 설정
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- -->
<bean id="myLogging" class="edu.njupt.zhb.Logging"></bean>
<!-- AOP -->
<aop:config>
<aop:aspect id="logStudent" ref="myLogging">
<!-- pointcut -->
<aop:pointcut id="allMethod" expression="execution(* edu.njupt.zhb.*.*(..))"/>
<aop:before pointcut-ref="allMethod" method="beforeAdvice"/>
<aop:after pointcut-ref="allMethod" method="afterAdvice"/>
<aop:after-returning pointcut-ref="allMethod" returning="retVal" method="afterReturningAdvice"/>
<aop:after-throwing pointcut-ref="allMethod" throwing="ex" method="afterThrowingAdvice"/>
</aop:aspect>
</aop:config>
<bean id="student" class="edu.njupt.zhb.Student">
<property name="id" value="1012010638"></property>
<property name="name" value="Haibo Zheng"></property>
</bean>
</beans>
2.4 테스트
package edu.njupt.zhb;
/*
* $filename: TestMain.java,v $
* $Date: 2013-12-10 $
* Copyright (C) ZhengHaibo, Inc. All rights reserved.
* This software is Made by Zhenghaibo.
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*
*@author: ZhengHaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: [email protected]
*2013-12-10 Nanjing,njupt,China
*/
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student)context.getBean("student");
System.out.println("-------------");
student.getId();
System.out.println("-------------");
student.getName();
System.out.println("-------------");
student.print("Hi,I am a student");
System.out.println("-------------");
try{
student.printThrowException();
}catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
2.5 실행 결과:
2013-12-10 18:32:54 org.springframework.context.support.AbstractApplicationContext prepareRefresh
: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145e044: display name [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]; startup date [Tue Dec 10 18:32:54 CST 2013]; root of context hierarchy
2013-12-10 18:32:54 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
: Loading XML bean definitions from class path resource [applicationContext.xml]
2013-12-10 18:32:54 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1f4cbee
2013-12-10 18:32:54 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1f4cbee: defining beans [myLogging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,allMethod,student]; root of factory hierarchy
-------------
Logging:before...
Logging:after...
Logging:return :1012010638
-------------
Logging:before...
Logging:after...
Logging:return :Haibo Zheng
-------------
Logging:before...
Say:Hi,I am a student,Name = Haibo Zheng
Logging:after...
-------------
Logging:before...
Exception in Student.class...
Logging:after...
Logging:exception:java.lang.IllegalArgumentException: Exception from Student...
Exception from Student...
상술 한 방법 은 함 수 를 실행 하기 전에 자신의 논 리 를 추가 하 는 것 일 뿐이다.더 복잡 한 기능 을 완성 하면 함수 의 이름과 함수 의 매개 변수 와 값 등 정 보 를 알 아야 할 수도 있 습 니 다.이 때 저 희 는 Logging 류 만 수정 하면 됩 니 다. 다음 과 같이 수정 할 수 있 습 니 다. (주로 Spring op 의 JointPoint 를 사 용 했 습 니 다)
/*
* $filename: Logging.java,v $
* $Date: 2013-12-10 $
* Copyright (C) ZhengHaibo, Inc. All rights reserved.
* This software is Made by Zhenghaibo.
*/
package edu.njupt.zhb;
import org.aspectj.lang.JoinPoint;
/*
*@author: ZhengHaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: [email protected]
*2013-12-10 Nanjing,njupt,China
*/
public class Logging {
public void beforeAdvice(JoinPoint jointPoint){
Object methodArgs[] = jointPoint.getArgs();//
for(Object arg:methodArgs){
System.out.println("Logging:args type="+arg.getClass().getName());
System.out.println("Logging:args value="+arg);
}
System.out.println("Logging:ClassName="+jointPoint.getTarget().getClass().getName());
System.out.println("Logging:MethodName="+jointPoint.getSignature().getName());
System.out.println("Logging:before... ");
}
public void afterAdvice(){
System.out.println("Logging:after... ");
}
/**
*
* @param retVal
*/
public void afterReturningAdvice(Object retVal){
if(retVal==null){
return;
}
System.out.println("Logging:return :"+retVal.toString());
}
public void afterThrowingAdvice(IllegalArgumentException ex){
System.out.println("Logging:exception:"+ex.toString());
}
}
현재 실행 결 과 는:
2013-12-10 19:44:07 org.springframework.context.support.AbstractApplicationContext prepareRefresh
: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145e044: display name [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]; startup date [Tue Dec 10 19:44:07 CST 2013]; root of context hierarchy
2013-12-10 19:44:07 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
: Loading XML bean definitions from class path resource [applicationContext.xml]
2013-12-10 19:44:07 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@145e044]: org.springframework.beans.factory.support.DefaultListableBeanFactory@787d6a
2013-12-10 19:44:07 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@787d6a: defining beans [myLogging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,allMethod,student]; root of factory hierarchy
-------------
Logging:ClassName=edu.njupt.zhb.Student
Logging:MethodName=getId
Logging:before...
Logging:after...
Logging:return :1012010638
-------------
Logging:ClassName=edu.njupt.zhb.Student
Logging:MethodName=getName
Logging:before...
Logging:after...
Logging:return :Haibo Zheng
-------------
Logging:args type=java.lang.String
Logging:args value=Hi,I am a student
Logging:args type=java.lang.Integer
Logging:args value=20
Logging:ClassName=edu.njupt.zhb.Student
Logging:MethodName=print
Logging:before...
Say:Hi,I am a student,Name = Haibo Zheng,age = 20
Logging:after...
-------------
Logging:ClassName=edu.njupt.zhb.Student
Logging:MethodName=printThrowException
Logging:before...
Exception in Student.class...
Logging:after...
Logging:exception:java.lang.IllegalArgumentException: Exception from Student...
Exception from Student...
허락 없 이 상업 목적 에 사용 할 수 없다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.