Spring - how to implement a specific implementation of an interface?

I need to introduce @Autouired specific implementation of a class of service.

Service Interface:

public interface PostService { ... } 

Implementation:

 @Service("postServiceImpl") public class PostServiceImpl implements PostService { ... } 

Methods in the service: @Transactional annotation

And now I want to add postServiceImpl to my controller, because I need to use one method from the implementation that is missing from the interface:

 @Autowired @Qualifier("postServiceImpl") private PostServiceImpl postService; 

I get a NoSuchBeanDefinitionException with the following message:

There is no qualification bean of the type [(...). PostServiceImpl] found for the dependency: at least 1 bean is expected that qualifies as an autowire candidate for this dependency.

when I change the field in my controller to:

 private PostService postService 

It works, but I cannot use a specific method from PostServiceImpl.

+7
java spring dependency-injection service autowired
source share
1 answer

Since your methods are annotated with @Transactional , spring will create a proxy at run time to enter the transaction control code. By default, spring uses the Dynamic Proxy JDK to proxy which proxies are based on interfaces.

So, in this case, spring creates another class that implements the PostService interface and creates a bean of this class. It is definitely not possible to do this for PostServiceImpl , as these are siblings. However, if you really want to use autwire in the class, you can force spring to use the CGLib proxy instead, which proxies use subclasses. This can be done by setting proxyTargetClass=true to the @EnableTransactionManagement annotation if you are using a Java based configuration.

+9
source share

All Articles