Spring入门-注解方式声明切面

pom.xml添加依赖

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>

切面代码

/**
 * 切面代码
*/
@Aspect
@Component
public class Advice {

@Before("execution(* com.msb.SpringAop.UserServiceImpl.add*(..))")
public void check(){
    System.out.println("权限检查....");
}

@After("execution(* com.msb.SpringAop.UserServiceImpl.add*(..))")
public void log(){
    System.out.println("日志记录....");
}
}

业务代码

/**
 * 业务代码
*/
public interface UserService {
//添加
void add() throws Exception;
//删除
void del() throws Exception;
}

接口实现类

/**
* 接口实现类
* @Service注解如果没有明确设置id值,那默认的id值为类名首字母小写
*/
@Service
public class UserServiceImpl implements UserService {

public void add() throws Exception {
    System.out.println("添加成功....");
}

public void del() throws Exception {
    System.out.println("删除成功....");
}
}

applicationContext.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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<!--扫描指定路径,自动注入注解-->
<context:component-scan base-package="com.msb"/>

<!--自动为Spring容器中那些配置@aspectJ切面的bean创建代理-->
<aop:aspectj-autoproxy/>
</beans>

测试类

public class AopTest {
@Test
public void test() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContextAnnotation.xml");
UserService service = (UserService)app.getBean("userServiceImpl");
service.add();
service.del();
}
}

运行结果(这里在配置是文件中我们只针对了add方法前后织入了通知)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值