接口
package com.hk.spring.annotation;
public interface ISomeService {
public void doFirst();
public void doSecond();
public String doThird();
}
接口实现
package com.hk.spring.annotation;
public class ISomeServiceImpl implements ISomeService {
@Override
public void doFirst() {
System.out.println("主业务逻辑doFirst执行");
}
@Override
public void doSecond() {
System.out.println("主业务逻辑doSecond执行");
}
@Override
public String doThird() {
System.out.println("主业务逻辑doThird执行");
return "ABC";
}
}
切面类
package com.hk.spring.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* 定义一个简单的POJO类作为切面
* @author 浪丶荡
*
*/
@Aspect
public class MyAspect {
@Before("execution(* *..ISomeService.doFirst(..))")
public void before(){
System.out.println("前置方法");
}
}
配置
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="someService" class="com.hk.spring.annotation.ISomeServiceImpl"></bean>
<bean id="myAspect" class="com.hk.spring.annotation.MyAspect"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
测试
package com.hk.spring.annotation
import org.junit.Test
import org.springframework.context.ApplicationContext
import org.springframework.context.support.ClassPathXmlApplicationContext
public class Mytest {
@Test
public void test1(){
String resoure = "com/hk/spring/annotation/applicationContext.xml"
ApplicationContext ac = new ClassPathXmlApplicationContext(resoure)
ISomeService service = (ISomeService) ac.getBean("someService")
service.doFirst()
service.doSecond()
service.doThird()
}
}
结果
前置方法
主业务逻辑doFirst执行
主业务逻辑doSecond执行
主业务逻辑doThird执行