註解配置aop

xml

<context:component-scan base-package="dao,aspect" />//首先對要使用代理的包進行掃描<aop:aspectj-autoproxy></aop:aspectj-autoproxy>//作用是自動裝配代理

<?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:context="http://www.springframework.org/schema/context"
    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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
 <context:component-scan base-package="dao,aspect" />
</beans>

Test.java

package test;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import dao.impl.UserDaoImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:ApplicationContext2.xml")
public class Test {
	@Autowired
	UserDaoImpl userdao1;
	
	@org.junit.Test
	public void test() {
		
		userdao1.addUser();
	}
}

代理類

package aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAspect {
	@Pointcut("execution(* dao..*(..))")
	public void pointCut() {
		
	}
	
	@Before("pointCut()")
	public void before() {
		System.out.println("前置");
	}
	@After("pointCut()")
	public void after() {
		System.out.println("最終通知");
	}
	@AfterReturning("pointCut()")
	public void afterReturning() {
		System.out.println("後置通知");
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章