有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Spring@Bean方法中返回接口的局限性

我在阅读@Bean方法的Spring文档时遇到了以下段落:

You can also declare your @Bean method with an interface (or base class) return type, as the following example shows:

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

However, this limits the visibility for advance type prediction to the specified interface type (TransferService). Then, with the full type (TransferServiceImpl) known to the container only once, the affected singleton bean has been instantiated. Non-lazy singleton beans get instantiated according to their declaration order, so you may see different type matching results depending on when another component tries to match by a non-declared type (such as @Autowired TransferServiceImpl, which resolves only once the transferService bean has been instantiated).

接下来的一段提到:

If you consistently refer to your types by a declared service interface, your @Bean return types may safely join that design decision. However, for components that implement several interfaces or for components potentially referred to by their implementation type, it is safer to declare the most specific return type possible (at least as specific as required by the injection points that refer to your bean).

有人能解释一下前几段的意思吗?我知道为接口编程是一种很好的做法。然而,当与@Bean方法一起使用时,似乎存在某种限制


共 (1) 个答案

  1. # 1 楼答案

    如果您像上面列出的那样定义bean:

        @Bean
        public TransferService transferService() {
            return new TransferServiceImpl();
        }
    

    然后,解析以下bean将始终有效:

    @Autowired
    TransferService transferService;
    

    但是尝试自动连接混凝土类并不总是有效的,因为Spring一开始还不知道这一点。它只知道在单例bean被实例化之后如何注入实现(也就是说,其他一些类已经@Autowired了接口)

    @Autowired 
    TransferServiceImpl transferService;
    

    ps:不要使用字段注入,而是使用构造函数。在这里展示现场注入,以保持简洁