基于传递给方法的参数,我需要从许多Spring Bean中进行选择,这些Spring Bean是同一类的实现,但是配置了不同的参数。

例如。如果用户A调用该方法,则我需要在bean A上调用dooFoo(),但是如果它是用户B,那么我就需要仅在bean B上调用完全相同的方法。

除了将所有bean粘贴在映射中并从传递给我的方法的参数中派生 key 之外,还有“Springier”方法可以做到这一点吗?

最佳答案

好像您想要使用应用程序上下文作为注册表的ServiceLocator

请参阅ServiceLocatorFactoryBean支持类,以创建将键映射到Bean名称的ServiceLocators映射,而无需将客户端代码耦合到Spring。

另一种选择是使用命名约定或基于注释的配置。

例如,假设您使用@ExampleAnnotation("someId")注释服务,则可以使用以下服务定位器之类的内容来检索它们。

public class AnnotationServiceLocator implements ServiceLocator {

    @Autowired
    private ApplicationContext context;
    private Map<String, Service> services;

    public Service getService(String id) {
        checkServices();
        return services.get(id);
    }

    private void checkServices() {
        if (services == null) {
            services = new HashMap<String, Service>();
            Map<String, Object> beans = context.getBeansWithAnnotation(ExampleAnnotation.class);
            for (Object bean : beans.values()) {
                ExampleAnnotation ann = bean.getClass().getAnnotation(ExampleAnnotation.class);
                services.put(ann.value(), (Service) bean);
            }
        }
    }
}

09-04 15:07
查看更多