springboot Autowired BeanNotOfRequiredTypeException


現象

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM