一、service类加注解
常规注解,bean的注解
package service;
import org.springframework.stereotype.Component;
@Component("myService")
public class MyService {
public void doMyService() {
System.out.println("This is my service");
}
}
二、aspect类加注解
component注解bean类,aspect注解表示切面,around注解放到方法上
package aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around(value="execution(* service.MyService.*(..))")
public Object function(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("start: "+joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
System.out.println("end: "+joinPoint.getSignature().getName());
return object;
}
}
三、配置文件
浏览包,再加个aop
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="aspect"></context:component-scan>
<context:component-scan base-package="service"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
四、运行测试
同上
五、测试类注解化
将主函数去掉,变成测试函数
配置文件,service类和aspect类同上
1. @RunWith(SpringJUnit4ClassRunner.class)
表示这是一个Spring的测试类
2. @ContextConfiguration("classpath:applicationContext.xml")
定位Spring的配置文件
3. @Autowired
给这个测试类装配MyService对象
4. @Test
测试逻辑,在此运行
package test;
import org.junit.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 service.MyService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MyTest {
@Autowired
MyService ms;
@Test
public void test() {
ms.doMyService();
}
/*
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
MyService ms = (MyService) context.getBean("myService");
ms.doMyService();
}*/
}