springboot Autowired BeanNotOfRequiredTypeException

简介:

v现象

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'xxxxImpl' is expected to be of type 'com.xxx.xxxImpl' but was actually of type 'com.sun.proxy.$Proxy62'

直接Autowired一个实现类,而不是接口

@Autowired
private XxxServiceImpl xxxService;

v解决方案

  1.  Autowired接口

  2.  使用EnableAspectJAutoProxy

复制代码
SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);
    }
}
复制代码

  设置proxy-target-class为true即使用cglib的方式代理对象,默认是jdk方式代理。

  jdk的动态代理不支持类注入,只支持接口方式注入。

 

v动态代理类型判断

复制代码
//org.springframework.aop.framework.DefaultAopProxyFactory     
  
//参数AdvisedSupport 是Spring AOP配置相关类     
  
public AopProxy createAopProxy(AdvisedSupport advisedSupport)     
  
        throws AopConfigException {     
  
    //在此判断使用JDK动态代理还是CGLIB代理     
  
    if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass()     
  
            || hasNoUserSuppliedProxyInterfaces(advisedSupport)) {     
  
        if (!cglibAvailable) {     
  
            throw new AopConfigException(     
  
                    "Cannot proxy target class because CGLIB2 is not available. "    
  
                            + "Add CGLIB to the class path or specify proxy interfaces.");     
  
        }     
  
        return CglibProxyFactory.createCglibProxy(advisedSupport);     
  
    } else {     
  
        return new JdkDynamicAopProxy(advisedSupport);     
  
    }     
  
}  
复制代码









本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/8428422.html,如需转载请自行联系原作者
目录
相关文章
|
21天前
|
Java
SpringBoot常用注解
SpringBoot常用注解
13 0
|
9月前
|
XML 缓存 运维
springboot注解(全)
springboot注解(全)
113 0
|
11天前
|
存储 JSON Java
Springboot注解总结
Springboot注解总结
|
4月前
|
Java 数据库 数据格式
springboot常用注解
springboot常用注解,超全,超详细
springboot常用注解
|
5月前
|
Java
Springboot手动获取bean
Springboot手动获取bean
|
8月前
|
XML Java 数据格式
SpringBoot-32-常用注解汇总2
SpringBoot-32-常用注解汇总2 在上一章节我们已经讲解了SpringBoot中Controller相关注解,没有看的可以了解一下SpringBoot-31-Controller相关注解详解
49 0
|
前端开发 Java 索引
40 个 SpringBoot 常用注解 上
40 个 SpringBoot 常用注解 上
84 0
40 个 SpringBoot 常用注解   上
|
XML JSON 负载均衡
SpringBoot中使用@ConfigurationProperties
SpringBoot中使用@ConfigurationProperties
|
Java
SpringBoot - @Value & @ConfigurationProperties(下)
SpringBoot - @Value & @ConfigurationProperties(下)
105 0