SpringFramework AOP(三)

本文详细介绍了Spring Framework的AOP(面向切面编程)特性,包括如何使用注解和XML方式定义切面,以及Spring如何通过JavaConfig和XML配置来发现并应用这些切面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring AOP 切面

注解的方式定义切面

定义一个切面

通过@Aspect注解定义一个切面

@Aspect
public class AspectsTest {
	//里面包含切点和通知
}

@Aspect注解

@Retention(RetentionPolicy.RUNTIME)
//只能使用来类上
@Target({ElementType.TYPE})
public @interface Aspect {
    String value() default "";
}

XML的方式定义切面

定义一个切面

创建一个切面的pojo

public class AspectsTest {
	//实现了切面的功能
}

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
       ">
    <!-- 将切面pojo注入spring容器中 --> 
    <bean id="aspectstest" class="com.test.springdome01.AspectsTest"></bean>
        
    <aop:config>
        <!-- 定义aspectstest bean为一个切面 -->
        <aop:aspect ref="aspectstest"></aop:aspect>
    </aop:config>
</beans>

Spring如何发现这个切面

通过JavaConfig配置方式
@Configuration
//启用AspectJ自动代理
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan
public class SpringConfig {
}
通过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
       ">
           <!-- 
           	注意上方:引入Spring-aop的约束 
           -->
			<!-- 启用AspectJ自动代理 -->
          	<aop:aspectj-autoproxy />
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值