Service接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.ledao.service;

/**
* @author LeDao
* @company
* @create 2022-02-17 20:29
*/
public interface StudentService {

/**
* 添加学生
*/
void add();

/**
* 删除学生
*/
void delete();

/**
* 修改学生
*/
void update();

/**
* 根据id查找学生
*/
void findById();
}

Service接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ledao.service.impl;

import com.ledao.service.StudentService;

/**
* @author LeDao
* @company
* @create 2022-02-17 20:30
*/
public class StudentServiceImpl implements StudentService {

@Override
public void add() {
System.out.println("添加学生");
}

@Override
public void delete() {
System.out.println("删除学生");
}

@Override
public void update() {
System.out.println("修改学生");
}

@Override
public void findById() {
System.out.println("根据id查找学生");
}
}

自定义切入类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.ledao.diy;

/**
* @author LeDao
* @company
* @create 2022-02-17 22:12
*/
public class DiyPointCut {

public void before(){
System.out.println("---------执行方法前---------");
}

public void after(){
System.out.println("---------执行方法后---------");
}
}

配置文件ApplicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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
https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--注册bean-->
<bean id="studentService" class="com.ledao.service.impl.StudentServiceImpl"/>
<bean id="diyPointCut" class="com.ledao.diy.DiyPointCut"/>

<aop:config>
<aop:aspect ref="diyPointCut">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.ledao.service.impl.StudentServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.ledao.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @author LeDao
* @company
* @create 2022-02-12 15:56
*/
public class MyTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
StudentService studentService = context.getBean("studentService", StudentService.class);
studentService.add();
}
}

结果截图

image-20220217222031941