Spring5学习2
aop实现的三种方式
第一种:Spring实现
service层
public interface IUserService {
public void add();
}
public class UserService implements IUserService{
@Override
public void add() {
System.out.println("增加方法执行了");
}
}
log层
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被方法执行了");
}
配置文件
<bean id="log" class="cn.xiong.log.log"></bean>
<bean id="UserService" class="cn.xiong.service.UserService"></bean>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* cn.xiong.service.UserService.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
测试类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserService userService = (IUserService) context.getBean("UserService");
userService.add();
}
}
第二种:自定义类实现
service层
public interface IUserService {
public void add();
}
public class UserService implements IUserService{
@Override
public void add() {
System.out.println("增加方法执行了");
}
}
自定义层
public class diy {
public void before(){
System.out.println("执行前----------");
}
public void after(){
System.out.println("执行后-------------");
}
}
配置文件
<bean id="UserService" class="cn.xiong.service.UserService"></bean>
<bean id="diy" class="cn.xiong.diy.diy"></bean>
<aop:config>
<aop:aspect id="diyaspect" ref="diy">
<aop:pointcut id="point" expression="execution(* cn.xiong.service.UserService.*(..))"/>
<aop:before method="before" pointcut-ref="point"></aop:before>
<aop:after method="after" pointcut-ref="point"></aop:after>
</aop:aspect>
</aop:config>
测试类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserService userService = (IUserService) context.getBean("UserService");
userService.add();
}
第三种:注解实现
service层
public interface IUserService {
public void add();
}
public class UserService implements IUserService{
@Override
public void add() {
System.out.println("增加方法执行了");
}
}
自定义层
@Aspect
public class diy {
@Before("execution(* cn.xiong.service.UserService.*(..))")
public void before(){
System.out.println("执行前----------");
}
@After("execution(* cn.xiong.service.UserService.*(..))")
public void after(){
System.out.println("执行后-------------");
}
}
配置文件
<bean id="UserService" class="cn.xiong.service.UserService"></bean>
<bean id="diy" class="cn.xiong.diy.diy"/>
<aop:aspectj-autoproxy/>
测试类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserService userService = (IUserService) context.getBean("UserService");
userService.add();
}