Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring error : BeanNotOfRequiredTypeException

My controller contains the following annotation :

@Resource(name="userService")
private UserDetailsServiceImpl userService;

and the service itself has the following :

@Service("userService")
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

However I receive the following error on startup :

Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDetailsServiceImpl' must be of type [myapp.service.UserDetailsServiceImpl], but was actually of type [$Proxy19]

like image 595
NimChimpsky Avatar asked Dec 17 '22 12:12

NimChimpsky


2 Answers

It should be

@Resource(name="userService")
private UserDetailsService userService;

Spring uses the interface type to make dependency injection, not the implementation type

like image 106
Jihed Amine Avatar answered Dec 19 '22 03:12

Jihed Amine


Change to (interface instead of concrete class):

@Resource(name="userService")
private UserDetailsService userService;

And live happily ever after.

Long version: at runtime, by default, Spring replaces your class with something that implements all the interfaces of your class. If you inject interface rather than a concrete type, you don't care what is the exact type implementing this interface.

In your case adding @Transactional annotation causes your bean to be replaced by AOP proxy with transaction capabilities. If you remove this annotation, your code will run fine. However, it is a good idea to depend on interfaces, not on concrete implementations.

like image 44
Tomasz Nurkiewicz Avatar answered Dec 19 '22 03:12

Tomasz Nurkiewicz