BeanNotOfRequiredTypeException due to autowired fields

前端 未结 9 1278
长发绾君心
长发绾君心 2020-12-02 12:07

I\'m still new to Spring MVC and while building my test project, I got this message from Tomcat logs:

SEVERE: Exception sending context initialized event to          


        
9条回答
  •  孤街浪徒
    2020-12-02 12:48

    I also have met the problem when execute unit test

    I created a mock service to implement the real service to override some method for easy to test some user case

    @Component
    public static class FooServiceImplMock extends FooServiceImpl {
        @Override
        protected void bar() {
            // do some specific loginc here 
        }
    }
    

    but when execute the test method

    @Autowired
    private Foo1ServiceImplMock foo1ServiceImplMock;
    

    I got below error

    Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'fooServiceImplTest.FooServiceImplMock' is expected to be of type 'com.foo.business.impl.FooServiceImplTest$FooServiceImplMock' but was actually of type 'com.sun.proxy.$Proxy97'
    

    Reason:

    There is method in FooServiceImpl used @Cacheable

    @Cacheable("eventTypes")
    

    And from javadoc of EnableCaching I know

    org.springframework.cache.annotation.EnableCaching 
    boolean proxyTargetClass()
    
    Indicate whether subclass-based (CGLIB) proxies are to be created as opposed to standard Java interface-based proxies. The default is false.
    

    So the resolve manner is explicitly to specify use CGLIB in spring application contenxt

     
    

提交回复
热议问题