이 기사는 Spring의 SpectJ Annotation 및 XML 구성을 사용하여 AOP의 구현을 보여줍니다.
다음은 SpectJ 주석을 사용하여 AOP를 구현하는 Java 프로젝트 입니다.
첫 번째는 클래스 경로 아래에있는 applicationcontext.xml 파일입니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : aop = "http://www.springframework.org/schema/aop"xmlns : tx = "http://www.springframework.org/schema/tx"xsi : schemalocation = "http://www.springframwork.org/schema/schema/schemas http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.spramework.org/schema/aop/sprring-5-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-enable anspectj Annotation-> <aop : <aopoproxy/> <Bean id ="usermanager "/>//////id id id ="anogmanager "/>/////id id id ="in id id = " </beans>
그런 다음 서비스 계층 인터페이스 및 구현 클래스가 있습니다.
패키지 com.jadyer.annotation; 공개 인터페이스 userManager {public void addUser (문자열 사용자 이름, 문자열 암호); 공개 void devuser (int userId); public String findUserById (int userId); public void modifyuser (int userId, 문자열 사용자 이름, 문자열 암호); } / *** 위의 UserManager는 서비스 계층의 인터페이스입니다.* 다음 userManagerImpl은 서비스 계층 인터페이스의 구현 클래스* / 패키지 com.jadyer.annotation; public class userManagerImpl은 userManager {public void addUser (String username, String password) {system.out.println ( "------ usermanagerImpl.adduser ()가 호출됩니다 -----"); } public void deLuser (int userId) {system.out.println ( "------- userManagerImpl.deluser ()가 호출됩니다 ------"); } public String findUserById (int userId) {System.out.println ( "------ userManagerImpl.FindUserById ()가 호출됩니다 ------"); "철제 생명"을 반환합니다. } public void modifyUser (int userId, 문자열 사용자 이름, 문자열 암호) {system.out.println ( "------- userManagerImpl.ModifyUser ()가 호출됩니다 ------"); }} 다음은 SpeciorJ로 표시된 항목 클래스입니다
패키지 com.jadyer.annotation; import org.aspectj.lang.annotation.fter; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.pointcut; @aspect public class securityhandler { /** * pointcut 정의 * @see pointcut pointcut의 이름은 addaddmethod ()입니다. 이 메소드는 반환 값과 매개 변수가 없습니다* @SEE이 메소드는 식별자이며*/@PointCut ( "execution (* add* (..))") // 개인 void addAddMethod () {}로 시작하는 모든 메소드와 일치합니다. /*** 조언 정의* @see는 어떤 Pointcut 가입을 나타냅니다 }} 마지막으로 클라이언트 테스트 클래스
패키지 com.jadyer.annotation; import org.springframework.context.applicationcontext; import org.springframework.context.support.classPathXmlApplicationContext; /*** AOP에 대한 Spring의 지원 : 주석 메소드 채택* @see -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- But there is a 전제 조건 : JDK 다이내믹 프록시이기 때문에 프록시를 생성하려면 클래스가 인터페이스를 구현해야합니다* @see 클래스에도 인터페이스가없고 스프링의 기본 AOP 구현이 여전히 사용되면 오류가 발생합니다. 오류가 발생합니다. 즉, 인터페이스 지향 프로그래밍* @see의 습관을 개발하십시오 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 추가 주석 지원 * @see * spring_home // dist // spring.jar * @see * spring_home // lib // log4j // log4j-1.2.jar * @see * spring_home // lib // jakarta-commons // commons-logging.jar * @see * spring_home // lib // lib // lib // lib // lib // SecurityHandler.java * @see 3. 주석을 사용하여 SecurityHandler를 측면 * @see 4. 주석을 사용하여 조언을 정의하고 포인트 컷 * @see 5를 정의하고 주석을위한 Spoction 지원을 활성화하고 IOC 컨테이너 * @see 6. @see 6. @see를 구성하십시오. --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- (userManager) factory.getBean ( "userManager"); usermanager.adduser ( "Zhang Qiling", "02200059"); }}
다음은 XML 구성 파일을 사용하여 AOP를 구현하는 Java 프로젝트 입니다.
첫 번째는 SRC의 루트 디렉토리에 위치한 ApplicationContext-cglib.xml 파일입니다.
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : aop = "http://www.springframework.org/schema/aop"xmlns : tx = "http://www.springframework.org/schema/tx"xsi : schemalocation = "http://www.springframwork.org/schema/schema/schemas http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.spramework.org/schema/aop/sprring-5-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-cglib proxy-<aop : <aop : <aop : <aoproxy prox-target class-clast-clath-clath-target clast의 힘 사용 id = "usermanager"/> <bean id = "securityhandler"/<aop : config> <aop : agage id = "securityAspect"ref = "securityHandler"> <aop : pointcut id = "addAddMethod"expression = "execution (* add* (..))") ")") ")") "checksecut": <checksecut-ref =. </aop : config> </beans> <!- Add (*add*(..))로 시작하는 모든 메소드를 일치시킵니다 (*add*(..)) com.jadyer.servcices.impl 패키지 실행 (*com.jadyer.servcices.impl.*. com.jadyer.services.impl.*. 추가*(..)) || 실행 (*com.jadyer.services.impl.*. del*(..)) ->
그런 다음 서비스 계층 인터페이스 및 구현 클래스가 있습니다.
패키지 com.jadyer.cglib; 공개 인터페이스 userManager {public void addUser (문자열 사용자 이름, 문자열 암호); 공개 void devuser (int userId); public String findUserById (int userId); public void modifyuser (int userId, 문자열 사용자 이름, 문자열 암호); } / *** 위의 UserManager는 서비스 계층 인터페이스입니다* 다음 userManagerImpl은 서비스 계층 인터페이스의 구현 클래스* / 패키지 com.jadyer.cglib; public class userManagerImpl {// incersManager {public void addUser (String username, String password) {system.out.println ( "------ usermanagerImpl.adduser ()가 호출됩니다 -----"); } public void deLuser (int userId) {system.out.println ( "------- userManagerImpl.deluser ()가 호출됩니다 -----"); } public String findUserById (int userId) {System.out.println ( "------ userManagerImpl.finduserByid ()가 호출됩니다 -----"); "Zhang San"을 반환합니다. } public void modifyUser (int userId, 문자열 사용자 이름, 문자열 암호) {System.out.println ( "------- userManagerImpl.ModifyUser ()가 호출됩니다 -----"); }} 다음은 ApplicationContext-cglib.xml에 지정된 항목 클래스입니다
패키지 com.jadyer.cglib; import org.aspectj.lang.joinpoint; /*** 클라이언트 호출 정보를 조언에 전달하십시오* @SEE는 조언에 조인 포인트 매개 변수를 추가하여 클라이언트 호출의 메소드 이름과 매개 변수 값을 얻을 수 있습니다. 우리는 주로 Spring* @see에서 제공하는 거래를 사용합니다. 다음은 샘플 코드 */ public class securityhandler {private void checksecurity (joinpoint jointopurity) {for (int i = 0; i <joinpoint.getargs (). length; i ++) {system.out.println (joinpoint.getargs () [i]); // 클라이언트가 호출 한 메소드의 매개 변수 값을 가져옵니다.} system.out.println (joinpoint.getSignature (). getName ()); // 클라이언트 System.out.println에서 호출 된 메소드 이름을 가져옵니다 ( "------ [CheckSecurity가 호출 됨] ------"); }} 마지막으로 클라이언트 테스트 클래스
패키지 com.jadyer.cglib; import org.springframework.context.applicationcontext; import org.springframework.context.support.classPathXmlApplicationContext; /** * @보다 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Since it is 상속, 대상 클래스* @see에 최종 선언을 사용하지 않는 것이 가장 좋습니다. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 우리 프록시 대상은 일반적으로 비즈니스 대상이기 때문에* @see --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- public class client {public static void main (String [] args) {ApplicationContext factory = new ClassPathXmlApplicationContext ( "ApplicationContext-cglib.xml"); // userManagerImpl이 UserManager 인터페이스를 구현할 때 Spring은 JDK Dynamic Proxy를 자동으로 사용합니다. // 프로젝트가 CGLIB 라이브러리를 도입하고 구성 파일에 CGLIB 프록시를 사용한 경우 Spring은 CGLIB 프록시 // userManager userManager = (userManager) accorory.getBean ( "userManager") 만 사용합니다. // userManagerImpl은 현재 userManagerImpl이 UserManager 인터페이스를 구현하지 않기 때문에 수신 유형에서 사용자 관리자 인터페이스를 사용할 수 없습니다 .//cglib 라이브러리가 프로젝트에 소개되었습니다. CGLIB 프록시는 구성 파일에서 사용되지 않지만 Spring은 CGLIB 프록시 userManagerImpl userManager = (userManagerImpl) factory.getBean ( "UserManager")을 자동으로 사용합니다. userManager.adduser ( "Wu Sansheng", "02200059"); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.