我们可以在Spring中没有任何实现的情况下自动装配接口吗? [英] Could we autowire an interface without any implementation in Spring?

查看:105
本文介绍了我们可以在Spring中没有任何实现的情况下自动装配接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们必须与合作伙伴共享代码库以进行开发,但是我们不想透露某些服务的实现.

We have to share our code base with a partner for developing, but we don't want to reveal the implementation of some services.

假设我们有一个接口FooService及其实现FooServiceImpl.

Say we have an interface FooService and its implementation FooServiceImpl.

public interface FooService
{
    void doSomething();
}

@Service
public class FooServiceImpl implements FooService
{
    @Override
    public String doSomething();
    {
        ...
    }
}

许多其他类自动将该服务连接到其中,并调用doSomething().例如:

Many other classes autowire this service in and call doSomething(). For example:

@Service
public class BarServiceImpl implements BarService
{
    @Autowired
    private FooService  fooService;

    @Override
    public String validate();
    {
        fooService.doSomething();
        ...
    }
}

如果我只是删除FooServiceImpl,当然在启动时会抛出NoSuchBeanException.如果我在自动连接FooService的所有地方都使用@Autowired(required = false),则只要调用doSomething(),就会在运行时抛出NullPointerException.

If I just delete FooServiceImpl, of course a NoSuchBeanException will be thrown while starting. If I use @Autowired(required = false) everywhere that FooService is autowired, a NullPointerException will be thrown at runtime whenever doSomething() gets called.

除了手动删除FooServiceImpl中的每个方法主体外,还有其他解决方法吗?

Besides the removal of each method body in FooServiceImpl manually, is there any other way to work this around?

感谢您的帮助.

推荐答案

我同意chrylis;您的用例听起来像您应该提供默认实现.我还将配置您的代码,以允许您的库用户提供自己的实现.通过Spring的@Conditional...批注,您可以轻松地做到这一点.具体来说,我认为您应该使用

I agree with chrylis; your use case sounds like you should ship a default implementation. I would also configure your code to allow the users of your library to provide their own implementation. Spring lets you do this easily with their @Conditional... annotations. Specifically, I think you should use @ConditionalOnMissingBean.

默认实现

@Component
public class DefaultFooServiceImpl implements FooService {
  @Override
  public void doSomething() {
    LOG.info("Using default implementation of doSomething(); nothing will happen");
  }
}

样品配置

@Configuration
public class ServiceConfig {
  @ConditionalOnMissingBean(FooService.class)
  @Bean
  DefaultFooServiceImpl defaultFooServiceImpl() {
    return new DefaultFooServiceImpl();
  }
}

当您的合作伙伴使用您的库时,他们将获得默认实现,并可以选择提供更好的实现.使用库时,可以创建一个ProprietaryFooServiceImpl bean,它将被注入.

When your partner uses your library, they get the default implementation, as well as the option to provide a better implementation. When you use your library, you can create a ProprietaryFooServiceImpl bean and it will get injected instead.

这篇关于我们可以在Spring中没有任何实现的情况下自动装配接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆