Spring入门-xml方式声明切面

pom.xml添加依赖

<!--注解式声明切面-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>

切面代码

/**
 * 切面代码
 */
public class Advice {
public void check(){
    System.out.println("权限检查....");
}

public void log(){
    System.out.println("日志记录....");
}
}

业务代码

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

接口实现类

/**
* 接口实现类
 */
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:context="http://www.springframework.org/schema/context"
   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/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">

<!--创建业务实现类对象-->
<bean id="service" class="com.msb.SpringXml.UserServiceImpl"/>

<!--创建切面类对象-->
<bean id="advice" class="com.msb.SpringXml.Advice"/>

<!--进行动态织入-->
<!--proxy-target-class默认:false,jdk动态代理;true,cdlib动态代理-->
<aop:config proxy-target-class="false">
    <!--声明切面对象-->
    <aop:aspect ref="advice">
        <!--定义切点-->
        <aop:pointcut id="addpointcut" expression="execution(* com.msb.SpringXml.UserServiceImpl.add*(..))"/>
        <!--定义前置通知-->
        <aop:before method="check" pointcut-ref="addpointcut"/>
        <!--定义后置通知-->
        <aop:after method="log" pointcut-ref="addpointcut"/>
    </aop:aspect>
</aop:config>
</beans>

测试类

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

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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值