aop

时间:2023-03-10 03:00:55
aop

做aop做一些事情:::

package cn.happy.spring04aop;

public interface ISomeService {
public void doSomeThing();
}
    package cn.happy.spring04aop;

public class SomeServiceImpl implements ISomeService {
//核心业务
@Override
public void doSomeThing() {
System.out.println("do ok? ok!yes");
} }

添加前置和后置

首先加入aop的jar包:aopalliance.jar

 package cn.happy.spring04aop.aop;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterAdvice implements AfterReturningAdvice {

    @Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("=====after==========");
}
}
package cn.happy.spring04aop.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;
/**
* @author Happy
*/
public class BeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("==============before=======");
} }

有了前置和后置之后,需要配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--如果一个类实现了一个接口 ,那么默认使用的代理是jdk代理 -->
<!--如果一个类没有实现了一个接口 ,那么默认使用的代理是cglib代理 -->
<!-- 被代理对象 SomeServiceImpl -->
<bean id="service" class="cn.happy.spring04aop.SomeServiceImpl"></bean>
<!--beforeadvice 前置通知 -->
<bean id="beforeAdvice" class="cn.happy.spring04aop.aop.BeforeAdvice"></bean>
<!-- AfterAdvice 后置通知 -->
<bean id="afterAdvice" class="cn.happy.spring04aop.aop.AfterAdvice"></bean>
<!-- aop -->
<aop:config>
<aop:pointcut expression="execution(public void *(..))" id="mypt"/>
<!--顾问 用来包含通知 -->
<aop:advisor advice-ref="beforeAdvice" pointcut-ref="mypt"/>
<aop:advisor advice-ref ="afterAdvice" pointcut-ref ="mypt"/>
</aop:config> </beans>

编写测试类:

package cn.happy.spring04aop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.happy.spring02printer.printer.Printer; public class MyTest {
@Test
public void aopTest(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("cn/happy/spring04aop/applicationContext.xml");
ISomeService service=(ISomeService)ctx.getBean("service");
service.doSomeThing();
}
}