service层的接口和实现类
package com.harris.service;
public interface UserService {
void add();
void delete();
void update();
void select();
}
package com.harris.service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加一个用户");
}
@Override
public void delete() {
System.out.println("删除一个用户");
}
@Override
public void update() {
System.out.println("修改一个用户");
}
@Override
public void select() {
System.out.println("查询一个用户");
}
}
Log 层
Log
通过继承MethodService 和配置文件实现AOP 切入
package com.harris.Log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的方法"+method.getName()+"被执行了");
}
}
AfterLog
package com.harris.Log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"返回结果为: "+o);
}
}
xml配置文件
<?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="userservice" class="com.harris.service.UserServiceImpl"/>
<bean id="log" class="com.harris.Log.Log"/>
<bean id="afterlog" class="com.harris.Log.AfterLog"/>
<!-- 方式一: 使用原生的Spring API 接口
需要导入AOP约束
-->
<aop:config>
<!--切入点 表达式: execution("位置") -->
<aop:pointcut id="pointcut" expression="execution(* com.harris.service.UserServiceImpl.*(..))"/>
<!--增强环绕 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试类
import com.harris.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userservice = (UserService) context.getBean("userservice");
userservice.add();
}
}
运行结果
遇到的一个小问题:BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
这是说明测试类的CPX的xml文件路径没有写对。
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");