错误"/>
spring AOP代理错误
1 报错信息
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'com.yang.service.UserServiceImpl' but was actually of type 'com.sun.proxy.$Proxy5'at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:392)at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)at com.yang.service.MyTest.main(MyTest.java:19)
其中,IOC容器内容为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xmlns:context=""xmlns:aop=""xsi:schemaLocation="://www.springframework/schema/beans/spring-beans.xsd://www.springframework/schema/context/spring-context.xsd://www.springframework/schema/aop/spring-aop.xsd"><context:annotation-config/><!--第一步,先注册bean--><bean id="userService" class="com.yang.service.UserServiceImpl"></bean><bean id="log" class="com.yang.log.Log"></bean><bean id="afterlog" class="com.yang.log.AfterLog"></bean><!--第二步,配置aop:需要在文件头导入支持--><aop:config>
<!--切入点,然后写表达式,表面在哪里类的方法进行切入,需要表面方法,参数等等情况--><aop:pointcut id="pointcut" expression="execution(* com.yang.service.UserServiceImpl.*(..))"/><!-- 执行环绕增加--><aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor><aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"></aop:advisor></aop:config></beans>
2 分析
spring AOP只能代理接口,不能代理具体的实现类。故需要修改下面的代码:
package com.yang.service;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @ClassName MyTest* @Author yang* @Description //TODO* @Date 22/07/23 16:36* @Version v1.0**/public class MyTest {public static void main(String[] args) {ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationcontext.xml");// 动态代理代理的是接口,不能写成实现类,故下面这个不行UserServiceImpl userService = classPathXmlApplicationContext.getBean("userService", UserServiceImpl.class);userService.add();System.out.println();}
}
正确的写法为:
package com.yang.service;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @ClassName MyTest* @Author yang* @Description //TODO* @Date 22/07/23 16:36* @Version v1.0**/public class MyTest {public static void main(String[] args) {ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationcontext.xml");// 动态代理代理的是接口,不能写成实现类,故下面这个不行UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);userService.add();System.out.println();}
}
更多推荐
spring AOP代理错误
发布评论