在编写代码的过程中出现了这样的错误:
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'studentServiceImpl' is expected to be of type 'com.service.impl.StudentServiceImpl' but was actually of type 'jdk.proxy2.$Proxy14'at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:384)at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1091)at com.test.TestDemo.main(TestDemo.java:14)
问了一下豆包,
- AOP 代理机制:Spring AOP 默认使用 JDK 动态代理(当目标对象实现了接口时),JDK 动态代理会创建一个实现了目标对象接口的代理类,而不是目标对象的实际类。因此,当你尝试直接使用目标对象的实现类类型来获取 Bean 时,就会抛出类型不匹配的异常。
- 类型获取错误:在代码中错误地使用了目标对象的实现类类型来获取 Bean,而应该使用其接口类型
Spring 中可以通过注解来实现AOP,通过注解来实现的具体步骤如下:
首先我们来看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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--定义扫描类 --><context:component-scan base-package="com"></context:component-scan><aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
aop:aspectj-autoproxy 是启动相关的支持aop
定义切面类:
java">@Aspect
@Component
public class LogAspect {@Before("execution(* com.service.impl.*.*(..))")public void beforePrintLog() {System.out.println("LogAspectbeforePrintLog");}public void afterReturnPrintLog() {System.out.println("LogAspectafterReturnPrintLog");}public void afterThrowingPrintLog() {System.out.println("LogAspectafterThrowingPrintLog");}public void afterPrintLog() {System.out.println("LogAspectafterPrintLog");}public void aroundPrintLog() {System.out.println("aroundPrintLog");}
}
切面类的注释除了@Aspect 之外,Spring 该有的注释也需要有 @Component
切点类:
java">package com.service.impl;import org.springframework.stereotype.Service;import com.service.StudentService;@Service
public class StudentServiceImpl implements StudentService{@Overridepublic void study() {System.out.println("正在学习...............");}}
注意的是:切点需要实现某个接口
测试类:
java">public class TestDemo {public static void main(String[] args) {ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");StudentServiceImpl ss=context.getBean("studentServiceImpl", StudentServiceImpl.class);ss.study();}}
但是会出现开头的错误,我们需要用到接口的回调,也就是用接口来创建目标类,修改为如下:
java"> public static void main(String[] args) {ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");StudentService ss=context.getBean("studentServiceImpl", StudentService.class);ss.study();}
上述就是通过Spring注解来实现SpringAOP的功能
希望对你有所帮助