本文介绍了Spring - 如何注入具体的接口实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过@Autowired注入服务类的具体实现。

I need to inject by @Autowired concrete implementation of a service class.

服务接口:

public interface PostService {
...
}

实现:

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

服务中的方法是@ Transactional注释

Methods in the service are with @ Transactional annotation

现在我想将postServiceImpl注入我的控制器 - 因为我需要使用实现中的一个方法,而不是在接口中:

And now I want to inject postServiceImpl to my controller - because I need to use one method from the implementation, that is not in the interface:

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

我得到 NoSuchBeanDefinitionException ,并显示以下消息:

I get NoSuchBeanDefinitionException with the following message:

当我将控制器中的字段更改为:

when I change the field in my controller to:

private PostService postService

它有效,但我不能使用PostServiceImpl中的特定方法。

it works, but I can't use a specific method from PostServiceImpl.

推荐答案

由于您的方法已注释 @Transactional ,spring将在运行时创建代理,以注入事务管理代码。默认情况下,Spring使用 JDK动态代理代理机制,代理基于接口。

Since your methods are annotated @Transactional, spring will create proxy at runtime, to inject transaction management code. By default Spring uses JDK Dynamic Proxy for proxying mechanism, which proxies based on interfaces.

因此,在这种情况下,spring会创建另一个类实现 PostService 接口,并创建该类的bean。绝对不能自动连接到 PostServiceImpl ,因为这些是兄弟姐妹。但是,如果你真的想在类上自动装配,你可以强制spring使用 CGLib 代理,代理使用子类。如果您使用的是基于Java的配置,则可以在 @EnableTransactionManagement 注释中设置 proxyTargetClass = true

So, in this case, spring creates another class which implements PostService interface, and creates bean of that class. Definitely that cannot be autowired to PostServiceImpl, as those are siblings. However, if you really want to autowire on class, you can force spring to use CGLib proxy instead, which proxies using subclassing. That you can do by setting proxyTargetClass=true in your @EnableTransactionManagement annotation, if you're using Java based config.

这篇关于Spring - 如何注入具体的接口实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:23