gpt4 book ai didi

java - Spring Autowiring 多个服务实现

转载 作者:搜寻专家 更新时间:2023-10-31 20:19:29 25 4
gpt4 key购买 nike

我有一个基本接口(interface)和两个实现

public interface AnimalService
{
public void eat();
}

@Service("animalService")
@Transactional
public class AnimalServiceImpl implements AnimalService
{
@Override
public void eat()
{
System.out.println("i'm eating");
}
}

@Service("birdService")
@Transactional
public class BirdServiceImpl extends AnimalServiceImpl
{
public void fly()
{
System.out.println("i'm flying");
}
}

在我的主要方法中尝试以这种方式调用这两个服务实现:

public class test
{
@Autowired
private AnimalService animalService;
@Autowired
@Qualifier("birdService")
private AnimalService birdService;

public static void main(String[] args)
{
animalService.eat();
birdService.eat();
birdService.fly();
}
}

这会产生编译错误,因为 birdService 找不到方法 fly()。然后我想也许原因是我 Autowiring AnimalService 而不是 BirdServiceImpl,所以我从这里更改了我的 Autowiring 代码:

   @Autowired
@Qualifier("birdService")
private AnimalService birdService;

更改为:

   @Autowired
private BirdServiceImpl birdService;

但这会给我一个运行时错误,即“找不到 bean BirdServiceImpl”。我谷歌了很多文档,有人说使用@Resource。但这对我不起作用。有人说在 Spring Context 中注册 bean,而我所有的 bean 注册都是通过注解完成的。我不想接触 Spring 上下文。

现在我的解决方案是添加一个新的接口(interface)

public interface BirdService extends AnimalService
{
public void fly();
}

然后让我的BirdServiceImpl去实现这个接口(interface)

    public class BirdServiceImpl extends AnimalServiceImpl extends BirdService
{
public void fly()
{
System.out.println("i'm flying");
}
}

我的主类更改为:

public class test
{
@Autowired
private AnimalService animalService;
@Autowired
private BirdService birdService;

public static void main(String[] args)
{
animalService.eat();
birdService.eat();
birdService.fly();
}
}

现在可以了。但对我来说,这并不完美。如果我使用纯 java,我可以只编写单个接口(interface)和多个实现。在主要方法中,我可以选择要使用的实现。为什么在 Spring ,我必须为每个新实现构建一个新接口(interface)才能让我的程序运行。

我想知道我的场景是否有更好的方法?

最佳答案

在您的问题中,您实际上暴露了两个问题:

<强>1。继承问题

这个问题不依赖于Spring Framework,而是你对继承的误解造成的。如果您将服务声明为 AnimalService,显然您只能将其用作 AnimalService,而不管其实际实现如何。如果你想使用具体的实现方法,你需要转换你的对象。

<强>2。 “ Autowiring 类”问题

这应该在 Spring 中正常工作,所以如果您的代码不起作用取决于您的上下文配置。也许你也在你的应用程序中使用 AOP 或事务,如果是,则启用自动代理生成器。这可能会导致您的问题。

看看这个问题:Spring Autowiring class vs. interface? .并注意:

When using autoproxies, you need to program to the interface, not the implementation

<强>3。只是一个注释

如何在 Java 接口(interface)/类名末尾使用 ()

关于java - Spring Autowiring 多个服务实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28230570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com