在service层织入新的功能
dao层
package org.lanqiao.dao.impl;
import org.lanqiao.dao.StudentDao;
import org.springframework.stereotype.Repository;
@Repository("StudentDao")
public class StudentDaoImpl implements StudentDao {
public int deleteStudentById(Integer id) {
System.out.println("删除dao层。。。。");
return 1;
}
}
service层
package org.lanqiao.service.impl;
import org.lanqiao.dao.StudentDao;
import org.lanqiao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("StudentService")
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
public boolean deleteStudentById(Integer id) {
System.out.println("删除service层。。。。");
int b = studentDao.deleteStudentById(id);
return b>0;
}
}
通知类
package org.lanqiao.advise;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
public class StudentAdvisor {
Logger logger = Logger.getLogger(StudentAdvisor.class);
public void doBefore(JoinPoint jp){
logger.info("在业务之前......");
}
public void doAfter(JoinPoint jp){
logger.info("在业务之后.....");
}
}
xml配置文件(用来连接service和通知类)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--扫描包-->
<context:component-scan base-package="org.lanqiao"/>
<!--将通知类放入ioc容器管理-->
<bean id="studentAdvisor" class="org.lanqiao.advise.StudentAdvisor"/>
<!--aop的配置-->
<aop:config>
<!--定义切面,多个通知,可以定义多个切面,切面有通知和切入点构成,通知已经有了引用引用的时通知-->
<aop:aspect id="StudentAspect" ref="studentAdvisor">
<!--通知已经有了,在定义切入点,位置是一个表达式-->
<aop:pointcut id="StudentPC" expression="execution(* org.lanqiao.service.*.*(..))"/>
<aop:before method="doBefore" pointcut-ref="StudentPC"/><!--前置通知,引入切入点-->
<aop:after method="doAfter" pointcut-ref="StudentPC"/><!--后置通知,引入切入点-->
</aop:aspect>
</aop:config>
</beans>
测试类
import org.junit.Test;
import org.lanqiao.service.StudentService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
@Test
public void test(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
StudentService studentService = (StudentService) ac.getBean("StudentService");
studentService.deleteStudentById(2);
}
}
允许结果