码迷,mamicode.com
首页 > 编程语言 > 详细

springboot Autowired BeanNotOfRequiredTypeException

时间:2018-02-07 22:41:22      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:getc   cannot   对象   解决   void   proxy   factor   isp   static   

现象

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;

解决方案

  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的动态代理不支持类注入,只支持接口方式注入。

 

动态代理类型判断

//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);     
  
    }     
  
}  

 

springboot Autowired BeanNotOfRequiredTypeException

标签:getc   cannot   对象   解决   void   proxy   factor   isp   static   

原文地址:https://www.cnblogs.com/hujunzheng/p/8428422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!