如何在Spring中使用多个名称命名@Service?

Luc*_*cas 4 spring

我需要类似的东西:

@Named({"bean1", "bean2"})

@Service({"bean1", "bean2"})
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

Tod*_*odd 6

不直接是您拥有的方式。但是可以通过使用名称或名称列表将现有@Service(或@Component)重新定义为a @Bean来实现。

@Service("Service-A")
public class SampleService {
    public String doSomething() { return "Foo"; }
}

@Configuration
public class SampleConfig {

    @Bean(name = {"Service-B", "Service-C"})
    public SampleService createMirroredService(@Autowired SampleService service) {
        return service;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您有三个实例SampleService:(Service-A您的@ServiceService-B,和Service-C。之所以有效,是因为您定义了一个方法,只是使带@Bean注释的方法通过了实现,这具有创建别名的效果。确保在扫描中选择了配置类,并且它应该可以正常工作。

注意:尽管这可行,并且可能还有其他解决方案,但我无法想到需要此解决方案的情况。也许如果我要与一个已经存在的库集成,则无法更改。但是对于我来说,这并不是很迫切的需求,否则它们会value@Component阵列上制造。