Autowire field failed when bean implements some interface using Spring

I use Spring in my Java application, all @Autowired annotations still work.

A simplified example:

@Component public class MyBean implements MyInterface { ... } @Component public class MyOtherBean { @Autowired private MyBean myBean; ... } 

As soon as I try to run the application, I get:

java.lang.IllegalArgumentException: Can not set MyBean field MyOtherBean.myBean to $ProxyXX

  • The interface contains only two simple simple methods, and the class implements them.
  • Both classes are public and have an open default constructor. (I even tried to create them in tests.
  • As soon as I delete the implements section, everything works correctly.

What could be wrong in the implementation of the interface? What is $ProxyXX ?

+4
source share
2 answers

I suspect the problem is that Spring is introducing an AOP proxy that implements MyInterface - perhaps for transaction management or caching purposes. Are any of the MyBean methods annotated with @Transactional or annotated with any other annotation?

Ideally, you probably want to reference MyBean by interface type - this should fix the problem.

 @Component public class MyOtherBean { @Autowired private MyInterface myBean; ... } 

If you have more than one bean that implements MyInterface, then you always qualify your bean by name.

 @Component public class MyOtherBean { @Autowired @Qualifier("myBean") private MyInterface myBean; ... } 
+11
source

By default, Spring uses dynamic Java proxies to implement AOP when a bean implements an interface. The easiest and cleanest way to solve your problem is to make a program on interfaces and insert an interface created by a specific class:

 @Component public class MyOtherBean { @Autowired private MyInterface myBean; ... } 

See http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/htmlsingle/#aop-proxying on how to get Spring to always use CGLIB.

+4
source

Source: https://habr.com/ru/post/1482620/


All Articles