Spring - 如何注入具体的接口实现?

Spring - how to inject concrete interface implementation?

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

服务接口:

public interface PostService {
...
}

实施:

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

服务中的方法带有@Transactional注解

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

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

我收到 NoSuchBeanDefinitionException 并显示以下消息:

No qualifying bean of type [ (...) .PostServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

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

private PostService postService

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

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

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