(1).BeanPostProcessor接口
BeanPostProcessor接口作用是:如果我们需要在Spring容器完成Bean的实例 化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。
(2).代码实现
(1).创建MyBeanPostProcessot类
首先创建MyBeanPostProcessot类,该类实现了BeanPostProcessor接口
public class MyBeanPostProcessot implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
System.out.println("this is before"+o);
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
System.out.println("this is after");
return Proxy.newProxyInstance(MyBeanPostProcessot.class.getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object o1, Method method, Object[] objects) throws Throwable {
MyAspect myAspect = new MyAspect();
myAspect.before();
Object obj = method.invoke(o, objects);
myAspect.after();
return obj;
}
});
}
}
(2).创建IUserService接口
public interface IUserService {
/*
* 获得所有用户对象列表
* */
List<Object> getAllUser();
/*
* 保存用户
* */
boolean saveUser(Object User);
/*
* 根据用户uid删除该用户信息
* */
boolean deleteUser(int uid);
/*
* 更新指定用户信息
* */
boolean updateUser(Object obj);
}
(3).创建UserServiceImpl实现类
在实现类中需要加入@component注解,主要作用是把普通pojo实例化到spring容器中,相当于配置文件中的 < bean id="" class="" />
@Component("us")
public class UserServiceImpl implements IUserService {
@Override
public List<Object> getAllUser() {
System.out.println("getAllUser");
return new ArrayList<>();
}
@Override
public boolean saveUser(Object user) {
System.out.println("saveUser");
return true;
}
@Override
public boolean deleteUser(int uid) {
System.out.println("deleteUser");
return false;
}
@Override
public boolean updateUser(Object obj) {
System.out.println("updateUser");
return true;
}
}
(4).创建beans.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"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.aop07"/>
<bean class="com.aop07.MyBeanPostProcessot"/>
</beans>
(5).创建测试类
public class TestAOP07 {
@Test
public void Test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("aop07_beans.xml");
IUserService iu = ac.getBean("us",IUserService.class);
System.out.println(iu.getAllUser());
System.out.println(iu.updateUser(new Object()));
System.out.println(iu.saveUser(new Object()));
System.out.println(iu.deleteUser(1));
}
}