aop再解释
aop的重要性
Spring aop就是讲公共的业务(如日志,安全等)和领域业务结合。当执行领域业务时将会把公共业务加进来。实现公共业务的重复利用。领域业务更纯粹。程序员更专注于领域业务。其本质还是动态代理。
第二种方式实现aop:自定义类来实现
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"
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="cn.sxt.service.impl.UserServiceImpl"></bean>
<bean id="log" class="cn.sxt.log.Log"/>
<aop:config>
<aop:aspect ref="log">
<aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
UserServiceImpl.java
package cn.sxt.service.impl;
import cn.sxt.service.UserService;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("------添加用户数据------");
}
public int delete() {
System.out.println("------删除用户数据------");
return 1;
}
}
UserService.java
package cn.sxt.service;
public interface UserService {
public void add();
public int delete();
}
log.java
package cn.sxt.log;
public class Log {
public void before() {
System.out.println("------方法执行前------");
}
public void after() {
System.out.println("------方法执行后------");
}
}
Test.java
package cn.sxt.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.sxt.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
UserService userService =(UserService)ac.getBean("userService");
userService.delete();
}
}