목차
1. XML 구성을 기반으로 한 Spring AOP
2. 주석을 사용하여 AOP를 구성하십시오
3. SAGONTJ POINT-CUT 기능
4. AspectJ Notification Notes
5. 스프링 IOC 및 AOP를 구현하려는 구성 제로 구성
AOP (Aspect Oriented Programming)는 런타임 동안 사전 컴파일 방법과 동적 에이전트를 통해 수평 다중 모듈 통합 통합 제어를 구현하는 기술입니다. AOP는 OOP의 보충제이며 스프링 프레임 워크의 중요한 부분입니다. 비즈니스 로직의 여러 부분을 AOP를 사용하여 분리하여 비즈니스 논리의 다양한 부분 간의 커플 링을 줄이고 프로그램의 재사용 성을 향상 시키며 개발 효율성을 향상시킬 수 있습니다. AOP는 정적 직조와 동적 직조로 나눌 수 있다는 것은 컴파일 전에 대상 모듈에 직조 할 내용을 작성하는 것을 의미합니다. 동적 직조는 대상 모듈을 변경할 필요가 없습니다. Spring Framework는 AOP를 구현하고 주석을 사용하여 AOP를 구성하는 것이 XML 구성을 사용하는 것보다 더 편리하고 직관적입니다.
1. XML 구성을 기반으로 한 Spring AOP
AOP 함수를 구현하기위한 주석을 설명하기 전에 먼저 이전 학습을 사용하여 XML을 사용하여 Spring AOP 함수를 구성하여 비교 및 더 나은 이해를위한 것입니다.
1.1. 새로운 프로젝트를 작성하고 프로젝트의 pom.xml 파일은 다음과 같습니다.
<project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : schemalocation = "http://maven.apache.org/0.0.0.0.0.0.0.0.0.0.0.0.0 sd/maven-4.0.0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> com.zhangguo </groupid> <artifactid> spring052 </artifactid> <버전> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> spring052 </name> <url> http://maven.apache.org </url> <proferties> <project.build.sourceencoding> utf-8 </project.build.sourceend.sourceencing> 4.3 /속성> <pectionies> <pectionency> <groupId> junit </groupId> <artifactId> junit </artifactid> <Scope> 테스트 </scope> <버전> 4.10 </version> </dependency> <pectionement> <groupid> org.springframework </groupid> <artifactid> spring-context </artifactid> <bersion} </version> </fexendence> <groupid> org.aspect> </artifactid> </artifactid> /종속성> <pectionency> <groupId> cglib </groupid> <artifactid> cglib </artifactid> <bersion> 3.2.4 </version> </fectionency> </fectencies> </project>
1.2.
com.zhangguo.spring052./*** Public int add (int n1, int result = n1+n2; .println (n1+”-"+n1, int n2) {int result = n1-n2; 결과 = n1;1.3. AOP에서 사용해야하는 자바 코드는 다음과 같습니다.
package com.zhangguo.Spring052.aop01;import org.aspectj.lang.JoinPoint;/** * Notification class, cross-cut logic* */public class Advices { public void before(JoinPoint jp){ System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------1.4. 컨테이너 초기화에 필요한 XML 파일은 다음과 같습니다.
<? xml version = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xsi = "http://ww.w.3.org/2001/xmlschema-instance : xmlns framework.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.xsd http://www.spramegame http://www.springframework.org http://wwwframecome. 3.xsd "> <!-프록시 객체-> <bean id ="math "> </bean> <!-알림-> <bean id ="advices "> </bean> <!-aop configuration-> <aop : config proxy-target class ="true "> <!-section-> <aop : afformes"> <aop : <aop : point : <aop : point : <aop : point : <aop : point : <aop : point : <aop : point : point : expression = "execution (* com.zhangguo.spring052.aop01.math.* (..))"id = "pointcut1"/> <!-Connect Notification Method and Point-Cut-> <aop : "pointcut-ref ="pointcut1 "/> <aop : after"pointcut-</aop /콩>
1.5. 테스트 코드 테스트는 다음과 같습니다.
com.zhangguo.spring052.aop01; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public static void main (string [] argpication actx) "); 수학 수학 = ctx.getBean ("math ", math.class); int n1 = 100, n2 = 5; Math.Sub (N1, N2);실행 결과 :
2. 주석을 사용하여 AOP를 구성하십시오
2. 이전 예제 <!-프록시 객체-> <bean id = "math"> </bean>에서 XML 구성 파일에 Bean을 추가하는 것과 같습니다. 수학 클래스의 코드는 다음과 같습니다.
com.zhangguo.spring052.aop02; import org.springframework.stereotyp.service;/*** public class math {int n1, int n2) {n1+n2+"+n2; /대체 public int sub (int n1, int n2) {int result = n1-n2; System.out.println (N1+”= "+결과); println (n1+"/"+n2+"="+결과)};2.
com.zhangguo.spring052.aop02; import org.aspectj.lang.joinpoint; import org.aspectj.lang.aspect; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.be org org.springopport. component @public class advices {@before ( "execution (* com.zhangguo.Spring052.aop02.Math.*(..))") public void before(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------위의 코드는 기본적으로 다음 구성과 동일합니다.
<!-> <bean id = "advices"> </bean> <!-AOP 구성-> <aop : config proxy-target class = "true"> <!-섹션-> <advices "> <!-슬라이스 포인트-> <aop : pointcut expression ="execution (* com.zhanggu. 1 "/> <!-연결 알림 메소드와 포인트-> <aop : 이전 메소드 ="pointcut-Ref = "pointcut-Ref ="pointcut1 "/> <aop : method ="After " PointCut-Ref = "PointCut1"/> </aop : Aspect> </aop : config>
2.
<? xml version = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xsi = "http://ww.w.3.org/2001/xmlschema-instance : xmlns framework.org/schema/p "xmlns : aop ="http://www.springframework.org/schema/aop "xmlns : context ="http://www.springframework.org/schema/context " xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/conxtpp./sww.sww ema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/spring-aop-4.3.xsd "> <context : component-scan base-package = "com.zhangguo.spring052.aop02"> </context : component-scan> <aop : agage-autoproxy proxy-target class = "true"> </aop : agage-autoproxy> </bans>
2.4. 테스트 실행 코드.
com.zhangguo.spring052.aop02; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public static void main (string [] argps) Math Math = Ctx.getBean ( "Math", Math.class); Math.Sub (N1, N2);
실행 결과 :
3. SAGONTJ POINT-CUT 기능
접선 기능은 정확한 횡단 논리적 위치에 위치 할 수 있습니다. 우리는 실행을 사용했습니다. 다른 타겟팅.
@aspectj는 Spring에 의해 지원되는 AspectJ Expressions를 설명하기 위해 Special Point-Cut 표현식을 사용합니다.
메소드 포인트 컷 함수 : 대상 클래스 메소드 정보를 설명하여 연결 지점을 정의합니다.
메소드 파라미터 포인트 컷 함수 : 대상 클래스 메소드의 매개 변수 정보를 설명하여 연결 지점을 정의합니다.
대상 클래스 포인트 컷 함수 : 대상 클래스 유형 정보를 설명하여 연결 지점을 정의합니다.
에이전트 클래스 포인트 컷 함수 : 프록시 클래스 정보를 설명하여 연결 지점을 정의합니다.
일반적인 측면 j 발현 함수 :
가장 일반적으로 사용되는 포인트 컷 함수는 실행 (<modifier mode>? <return type mode> <메소드 이름 모드> (<매개 변수 모드>) <예외 모드>?) 포인트 컷 함수입니다.
각 지점 탄젠트 함수의 기능을 보여주기 위해 이제 새로운 클래스 스트 루틸이 추가되고, 클래스는 다음과 같습니다.
com.zhangguo.spring052.aop03; import org.springframework.stereotyp.component ( "strutil") public class strutil {public void show () {System.out.println ( "Hello Strutil!");테스트 코드는 다음과 같습니다.
com.zhangguo.spring052.aop03; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public static void main (string [] argps) ); imath math = ctx.getbean ( "math", int n1 = 100, n2 = 5; Math.Sub (N1, N2);
3.1. 포인트 컷 함수 실행, 알림 및 섹션은 다음과 같습니다.
com.zhangguo.spring052.aop03; import org.aspectj.lang.joinpoint; import org.aspectj.lang.aspect; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.be org org.springopport.compringoption. component @public class advices {@before ( "execution (* com.zhangguo.spring052.math.*(..)) ") public void prever (joinpoint.out.println ("------------------------------------------------------------- 3 패키지는 @After로 잘라냅니다 ( "execution (*com.zhangguo.spring052.aop03.*.*(..))") public void After (joinpoint jp) { System.out.println ( "--------------------------------------------작업 결과는 다음과 같습니다.
실행 (<modifier mode>? <리턴 유형 모드> <메소드 이름 모드> (<매개 변수 모드>) <예외 모드>?)
3.2
//within point-cut function//com.zhangguo.Spring052.aop03 package all methods of all classes are cut into @After("within(com.zhangguo.Spring052.aop03.*)") public void after(JoinPoint jp){ System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------3.3
//this point-cut function//Implements any connection point of the proxy object of the IMath interface @After("this(com.zhangguo.Spring052.aop03.IMath)") public void after(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------3.4. Args 포인트 기능
//args point-cut function//Requires that the method has two int type references before it will be weaved into the cross-cutting logic @After("args(int,int)") public void after(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 매개 변수 유형이 기본 데이터 유형이 아닌 경우 패키지 이름이 필요합니다.
3.5. @Annot Point-Cut 함수
먼저 메소드에 주석을 달 수있는 주석을 사용자 정의하십시오.
패키지 com.zhangguo.spring052.aop03; import java.lang.annotation.documented; import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.antoT (@electorpe). resentention(retentionpolicy.runtime)@documentedpublic @interface myanno {} //@annotation point-cut 함수 // 메소드가 com.zhangguo.spring052.aop03.aop03.myanno를 횡단 절단 로직 @after ( "@annotation (com.zhangguo.spring052.aop03.myanno)")에 직조하려면 메소드가 주석을 달아야합니다. } com.zhangguo.spring052.aop03; import org.springframework.stereotyp.component ( "strutil") public class strutil {@myanno public void show () {System.out.out.println ( "Hello Strutil!");실행 결과 :
@와 함께 다른 포인트 커팅 함수는 주석입니다
4. AspectJ Notification Notes
SAGONTJ에는 6 개의 알림 주석이 있으며, 5 개는 일반적으로 사용되며 소개가 적습니다.
먼저 다음 코드에 표시된대로 접선 기능의 내용은 정확히 동일합니다.
com.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; import org.aspectj.lang.aspect; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.be org org.springopport.compringoption. component @public class advices {@before ( "execution (* com.zhangguo.Spring052.aop04.Math.*(..))") public void before(JoinPoint jp){ System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------먼저 탄젠트를 정의한 다음 다음과 같이 멀티 플렉스 할 수 있습니다.
com.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.be org.aspectj.lang.annotation.spointcut; springframwork. Component@Aspectpublic Class Advices { // @PointCut ( "* com.zhangguo.spring052.math.* (..)))) public void pointcut () {} @before ("pointCut () "(jop point jp) {System.out.out.println ("------------------------------------------------------------------------------------------------------------------------------------------------------------- ));} @ @"pointcut ()") public void (joinpoint jp) { System.out.println ( "--------------------------------------------Advices.java 파일을 수정하고 다음과 같이 다양한 알림 유형을 추가하십시오.
패키지 com.zhangguo.spring052.aop04; import org.aspectj.lang.joinpoint; import org.aspectj.lang.proceedingjoinpoint; import org.aspectj.lang.annotation.after; import org.aspectj.lang.ennotation.afterreturning; import org.asj.lang ang.annotation.around; import org.aspectj.lang.annotation.around; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.fore; import org.aspectj.lang.annotation.pointcut; import org.springframework.stereotyp.component;/*** 알림 클래스, cross-cut logic*/@compublic@poplic class advices { "execution (* com.zhangguo.spring05.math.a* (..))) ice @before ( "pointcut ()") public void 이전 (joinpoint jp) { System.out.println(jp.getSignature().getName()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Throwable{ System.out.println(pjp.getSignature().getName()); System.out.println("-------------------------------------------"); Object result=pjp.proceed(); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ jppoint.out.println (jp. getSignature (). getName ()); "+결과); -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------. System.out.println(jp.getSignature().getName()); System.out.println("Exception message: "+exp.getMessage()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------실행 결과 :
5. 스프링 IOC 및 AOP를 구현하려는 구성 제로 구성
원래 예제를 기반으로 구성이없는 구성을 달성하기 위해 다음과 같이 새 사용자와 같은 클래스를 추가합니다.
com.zhangguo.spring052.aop05; public class user {public void show () {System.out.println ( "사용자 개체");이 클래스에는 주석이 달리지 않으며 컨테이너는 자동으로 관리되지 않습니다. XML 구성 파일이 없으므로 하나를 구성 정보로 사용하면 ApplicationCFG.java 파일은 다음과 같습니다.
패키지 com.zhangguo.spring052.aop05; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configpration; import org.spring figuration // <beans/>@componentscan과 유사한 현재 클래스를 컨테이너로 표현하는 데 사용되는 구성 클래스 (basepackages = "com.zhangguo.spring052.aop05") // 스캔 범위는 XML 구성 <context : component-scan/>@enableaspectjautoProxy (proxyTargetCan = true)의 노드와 동일합니다 <bean id = getUser/> @bean public user getUser () {return new user ()}에 해당합니다.이 클래스의 각 부분은 기본적으로 XML 구성과 일대일 관계를 맺고 있습니다. 테스트 코드는 다음과 같습니다.
com.zhangguo.spring052.aop05; import org.springframework.context.applicationcontext; import org.springframework.context.annotation.annotationconfigapplicationcontext; import org.springframework.scramppution.spputpplication (classpport) {// 클래스 ApplicationContext CTX = New를 통해 컨테이너 초기화 AnnotationConfigationContect는 CTX.GetBean (Math.class) (N1, N2); = ctx.getBean ( "getUser", user.show (); advices.java는 변경없이 위와 동일합니다. 실행 결과는 다음과 같습니다.
위의 내용은이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다.