Getting Spring Error “Bean named 'x' must be of type [y], but was actually of type [$Proxy]” in Jenkins

前端 未结 2 2074
清酒与你
清酒与你 2020-12-03 07:30

I have been debugging this for awhile now, and I\'m hoping someone could shed some light here.

I have a Maven project that is added into Jenkins, using JDK 1.6. I\'m

相关标签:
2条回答
  • 2020-12-03 07:57

    Excerpt from question comments above:

    Are you running Cobertura, Sonar or other code-instrumenting tool on Jenkins? Note that mvn site might also be configured to include Cobertura report in generated site.

    The problem with Cobertura is that it performs pretty heavy byte-code instrumentation including the addition of some custom interfaces. When Spring starts up it generates proxies for beans. If bean has at least one interface, it uses standard Java proxy. Otherwise it tries to create class-based proxy.

    I guess in your case the CGLIB class proxy was used but after Cobertura instrumentation Spring fall back to java proxies. This caused startup error because dependency injection expected class (or CGLIB subclass).

    To cut long story short, force CGLIB class proxies and you'll be fine:

    <aop:config proxy-target-class="true"/>
    
    0 讨论(0)
  • 2020-12-03 08:14

    Got the same problem using AspectJ.

    There was a bean w

    @Configuration public class MyConfig{
    
    @Value("classpath:some.properties")
    private Resource theResource;
    
    @Bean
    public  SomeResource getSomeResource()
    {
        return  SomeResource.getOne(theResource);
    }
    /******/
     
      @Component
    public class SomeResource{
       public SomeResource(Resource r) {...}
       public static getOne(Resource r} { return new SomeResource(r); }
    

    This works fine until AOP/AspectJ is enabled. The injection validates that the SomeResource bean is from class SomeResource, but since it is a Proxy it crashes.

    SOlution: use GLIBC proxy for that Bean instead of AspectJ proxies.

    @EnableAspectJAutoProxy(proxyTargetClass=false)
    public class SomeResource{...}
    

    Makes no sense, but now got a clearer message

    WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils
     (file:/path/spring-core/5.2.10.RELEASE/spring-core-5.2.10.RELEASE.jar) to method
    java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
    WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
    

    Meaning Java prevent reflection on this method.Either Spring or Java needs to fix that.

    0 讨论(0)
提交回复
热议问题