Spring3 context:component-scan和aop:aspectj-autoproxy联合使用时,无法检测到bean

在Spring3项目中,使用`context:component-scan`和`aop:aspectj-autoproxy`时遇到bean初始化成功但注解AOP无法生效的问题。通过调整配置,成功解决了bean初始化并能正常应用注解AOP进行切面处理。

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

1.项目

package com.cl.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//切面类
@Component
@Aspect
public class AopLog {

	// 前置通知
	@Before("execution(* com.cl.service.UserService.add(..))")
	public void begin() {
		System.out.println("前置通知");
	}

	//
	// 后置通知
	@After("execution(* com.cl.service.UserService.add(..))")
	public void commit() {
		System.out.println("后置通知");
	}

	// 运行通知
	@AfterReturning("execution(* com.cl.service.UserService.add(..))")
	public void returning() {
		System.out.println("最终通知");
	}

	// 异常通知
	@AfterThrowing("execution(* com.cl.service.UserService.add(..))")
	public void afterThrowing() {
		System.out.println("异常通知");
	}

	// 环绕通知
	@Around("execution(* com.cl.service.UserService.add(..))")
	public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		System.out.println("环绕通知开始");
		proceedingJoinPoint.proceed();
		System.out.println("环绕通知结束");
	}
}
package com.cl.service;

public interface UserService {

	void add();
}
package com.cl.service.impl;

import org.springframework.stereotype.Service;

import com.cl.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	public void add() {
		System.out.println("add User");
	}

}

完成。

运行报错

信息: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to com.cl.service.impl.UserServiceImpl
	at com.cl.test.TestAop.main(TestAop.java:13)

修改:执行成功,bean正确初始化了,但是不能使用注解AOP

 于是修改:成功使用注解AOP

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值