codeInitialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class com.alibaba.alibrain.quotareport.controller.QuotaReportDayController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class com.alibaba.alibrain.quotareport.controller.QuotaReportDayController at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562)
这个错误通常表示在创建Bean时无法生成CGLIB子类。原因可能是使用了final类或非可见类。
首先,我们需要确保被声明为Bean的类是可见的。在Java中,类的可见性由public、protected、private和默认(无修饰词)四个级别控制。 如果被声明为Bean的类是非公共的(即不是public修饰的),请确保该类所在的包(package)在Spring的扫描路径下,并且配置了正确的包扫描规则。 另外,您还应该检查类的修饰符是否正确。Spring不能将final类或非继承类(如接口)作为目标创建CGLIB代理对象。
有时,这个问题可能是由于Spring版本不兼容导致的。请确保您使用的Spring版本与您的项目和依赖项兼容。 如果您正在使用较旧的Spring版本,可以尝试升级到最新版本,以看是否解决了该问题。
除了CGLIB代理之外,Spring还支持其他代理模式,如JDK动态代理和AspectJ代理。 您可以尝试使用JDK动态代理或AspectJ代理来替代CGLIB代理。在Spring配置文件中,可以通过设置<aop:aspectj-autoproxy proxy-target-class="false"/>来启用JDK动态代理或AspectJ代理。
com.example.demo.controller; import org.springframework.stereotype.Controller; @Controller public class MyController { // Controller的具体实现代码 }在这个示例中,我们有一个MyController类用于处理请求,被声明为@Controller注解。 如果我们运行时遇到类似的错误:
plaintextCopy codeInitialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class com.example.demo.controller.MyController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class com.example.demo.controller.MyController我们可以采取以下几步解决该问题:
com.example.demo.controller; import org.springframework.stereotype.Controller; @Controller public class MyController { // Controller的具体实现代码 }如果修改不可行,我们可以尝试使用JDK动态代理或AspectJ代理来解决问题。在Spring配置文件中,配置如下的代理模式来启用JDK动态代理:
<aop:aspectj-autoproxy proxy-target-class="false"/>
这样,Spring将采用JDK动态代理而不是CGLIB代理来创建Bean。需要注意的是,JDK动态代理只能代理实现了接口的类。 通过以上几个步骤,我们可以解决由于使用了final类或非可见类而导致的Spring初始化Bean失败的问题,让我们的应用能够正常运行。
// 目标类 public class MyService { public void doSomething() { // 方法实现代码 } } // 堆代码 duidaima.com // 代理生成 Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(MyService.class); enhancer.setCallback(new MyMethodInterceptor()); // 创建代理对象 MyService proxy = (MyService) enhancer.create(); // 通过代理对象调用方法 proxy.doSomething();上述示例中,我们创建了一个MyService的代理对象proxy,并通过Enhancer类的create()方法生成了一个目标类MyService的子类,该子类继承了目标类的方法,并在MyMethodInterceptor回调对象中实现了对方法的增强逻辑。 总之,CGLIB代理是一种在运行时生成子类来实现对目标类的代理的技术,它具有继承代理、无需接口、更高性能和更丰富功能的特点。在Spring框架中,CGLIB代理被广泛用于实现AOP操作,提供了方便而强大的代理功能。