开发者

Spring error : BeanNotOfRequiredTypeException

开发者 https://www.devze.com 2023-03-18 17:21 出处:网络
My controller contains the following annotation : @Resource(name=\"userService\") private UserDetailsServiceImpl userService;

My controller contains the following annotation :

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

and the service itself has the following :

@Service("userService")
@Transactional
public class UserDetails开发者_StackOverflow社区ServiceImpl 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]


It should be

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消