3

I have a service bean (annotated with @Service) which implements the ApplicationListener inteface for T type of event objects that extend the ApplicationEvent abstract Class. There is a pretty simple and clear example of this in the Spring docs here

However when i attempt to inject this bean into other ones using @Autowired i get is:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [...] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotation {@org.springframework.beans.factory.annotation.Autowired(required=true)}

If i try to use something like @Resource then i get a class cast exception (attempting to inject a resource of one type but getting a Proxy).

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
nvrs
  • 720
  • 2
  • 17
  • 25

1 Answers1

6

If i try to use something like @Resource then i get a class cast exception (attempting to inject a resource of one type but getting a Proxy).

This sounds like you are trying to reference it by class, whereas it is wired as an interface-based JDK proxy.

If you have this class:

@Service
public class FooServiceImpl implements FooService{}

wire it as:

@Autowired
private FooService fooService;

not as:

@Autowired
private FooServiceImpl fooService;

Reference:

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Yeah, that worked (got the same answer on the Spring forums a while ago). Should i turn on Class proxies instead? – nvrs Jul 11 '11 at 14:28
  • @nvrs I find it preferable to use interfaces (read Effective Java by Joshua Bloch for explanation why). For one thing, it's easier to mock services for unit-tests. – Sean Patrick Floyd Jul 11 '11 at 14:30
  • That's fair enough. Still it's the only other reason i can see to program to an interface in this particular occasion (and of course the JDK proxying stuff) in the context that this Service is an implementation in the first place. – nvrs Jul 11 '11 at 14:45
  • 1
    @nvrs I know, when you have exactly one implementation class per interface, you begin to wonder why you should use interfaces in the first place. I understand that, but I still prefer using interfaces :-) – Sean Patrick Floyd Jul 11 '11 at 14:54