Spring 3中的Custom Autowire候选bean

时间:2013-02-21 00:53:22

标签: java spring dependency-injection annotations

假设我有一个服务接口ServiceInterface以及实现它的几个组件的以下结构:ProductAServiceProductBService我还有一个RequestContext bean,它有一个合格的财产,表示我们说目前正在处理ProductA或ProductB。然后,如何将自动装配或其他注释自动注入正确的实现(ProductAService或ProductBService)到需要它的某个服务(下面ServiceThatNeedsServiceInterface)。

public interface ServiceInterface {
  void someMethod();
}

@Component(name="ProductAService")
public class ProductAService implements ServiceInterface {
  @Override public void someMethod() { 
    System.out.println("Hello, A Service"); 
  }
}

@Component(name="ProductBService")
public class ProductBService implements ServiceInterface {
  @Override public void someMethod() { 
    System.out.println("Hello, B Service"); 
  }
}

@Component
public class ServiceThatNeedsServiceInterface {

  // What to do here???
  @Autowired
  ServiceInterface service;

  public void useService() {
    service.someMethod();
  }
}

@Component
@Scope( value = WebApplicationContext.SCOPE_REQUEST )
public class RequestContext {
  String getSomeQualifierProperty();
}

6 个答案:

答案 0 :(得分:11)

Spring Source在1.1.4版本中创建ServiceLocatorFactoryBean时引用了您的问题。为了使用它,您需要添加类似于下面的界面:

public interface ServiceLocator {
    //ServiceInterface service name is the one 
      //set by @Component
    public ServiceInterface lookup(String serviceName);
}

您需要将以下代码段添加到applicationContext.xml

<bean id="serviceLocatorFactoryBean"
    class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
    <property name="serviceLocatorInterface"
              value="org.haim.springframwork.stackoverflow.ServiceLocator" />
</bean>

现在,您的ServiceThatNeedsServiceInterface看起来与下面的类似:

@Component
public class ServiceThatNeedsServiceInterface {
    // What to do here???
    //  @Autowired
    //  ServiceInterface service;

    /*
     * ServiceLocator lookup returns the desired implementation
     * (ProductAService or ProductBService) 
     */ 
 @Autowired
     private ServiceLocator serviceLocatorFactoryBean;

     //Let’s assume we got this from the web request 
     public RequestContext context;

     public void useService() {
        ServiceInterface service =  
        serviceLocatorFactoryBean.lookup(context.getQualifier());
        service.someMethod();         
      }
}

ServiceLocatorFactoryBean将根据RequestContext限定符返回所需的服务。 除了spring注释,您的代码不依赖于Spring。 我为上面的

执行了以下单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:META-INF/spring/applicationContext.xml" })
public class ServiceThatNeedsServiceInterfaceTest {

    @Autowired
    ServiceThatNeedsServiceInterface serviceThatNeedsServiceInterface;

    @Test
    public void testUseService() {
    //As we are not running from a web container
    //so we set the context directly to the service 
        RequestContext context = new RequestContext();
        context.setQualifier("ProductAService");
        serviceThatNeedsServiceInterface.context = context;
        serviceThatNeedsServiceInterface.useService();

        context.setQualifier("ProductBService");
        serviceThatNeedsServiceInterface.context = context;
        serviceThatNeedsServiceInterface.useService();
    }

}

控制台将显示
您好,A服务
您好,B服务

一句警告。 API文档说明了 “这样的服务定位器......通常用于原型bean,即用于为每个调用返回一个新实例的工厂方法......对于单例bean,最好直接设置器或构造函数注入目标bean。”

我无法理解为什么这可能会导致问题。在我的代码中,它在对serviceThatNeedsServiceInterface.useService()的两个序列调用中返回相同的服务;

您可以在GitHub

中找到我的示例的源代码

答案 1 :(得分:3)

我能想到的唯一方法就是创建像FactoryBean这样的东西,它根据RequestContext属性返回相应的实现。这是我打了一个有你想要的行为的东西:

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;

public class InjectionQualifiedByProperty {

    @Controller
    @Scope(WebApplicationContext.SCOPE_REQUEST)
    public static class DynamicallyInjectedController {
        @Autowired
        @Qualifier("picker")
        Dependency dependency;

        @RequestMapping(value = "/sayHi", method = RequestMethod.GET)
        @ResponseBody
        public String sayHi() {
            return dependency.sayHi();
        }
    }

    public interface Dependency {
        String sayHi();
    }

    @Configuration
    public static class Beans {
        @Bean
        @Scope(WebApplicationContext.SCOPE_REQUEST)
        @Qualifier("picker")
        FactoryBean<Dependency> dependencyPicker(final RequestContext requestContext,
                                                 final BobDependency bob, final FredDependency fred) {
            return new FactoryBean<Dependency>() {
                @Override
                public Dependency getObject() throws Exception {
                    if ("bob".equals(requestContext.getQualifierProperty())) {
                        return bob;
                    } else {
                        return fred;
                    }
                }

                @Override
                public Class<?> getObjectType() {
                    return Dependency.class;
                }

                @Override
                public boolean isSingleton() {
                    return false;
                }
            };
        }
    }

    @Component
    public static class BobDependency implements Dependency {
        @Override
        public String sayHi() {
            return "Hi, I'm Bob";
        }
    }

    @Component
    public static class FredDependency implements Dependency {
        @Override
        public String sayHi() {
            return "I'm not Bob";
        }
    }

    @Component
    @Scope(WebApplicationContext.SCOPE_REQUEST)
    public static class RequestContext {
        @Autowired HttpServletRequest request;

        String getQualifierProperty() {
            return request.getParameter("which");
        }
    }
}

我使用此代码on Github放了一个工作示例。您可以使用以下命令克隆并运行它:

git clone git://github.com/zzantozz/testbed tmp
cd tmp/spring-mvc
mvn jetty:run

然后访问http://localhost:8080/dynamicallyInjected以查看一个依赖项的结果,并http://localhost:8080/dynamicallyInjected?which=bob查看另一个依赖项。

答案 2 :(得分:1)

我想,你错过了注释,告诉春天,你有一个自定义服务。 所以你的解决方案是在类名之前添加这个注释:

@Service("ProductAService")
public class ProductAService implements ServiceInterface {
  @Override public void someMethod() { 
    System.out.println("Hello, A Service"); 
  }
}

@Service("ProductBService")
public class ProductBService implements ServiceInterface {
  @Override public void someMethod() { 
    System.out.println("Hello, B Service"); 
  }
}

然后您可以自动连接它,但是为了使用特定服务,您必须添加注释Qualifier(),如下所示:

  @Autowired
  @Qualifier("ProductBService") // or ProductAService
  ServiceInterface service;

或者你可能只需要添加一个注释限定符(“你的bean名称”):)

答案 3 :(得分:1)

这可能会对您有所帮助:

使用

AutowireCapeableBeanFactory.autowireBean(Object existingBean)  

OR

AutowireCapeableBeanFactory.autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)

AutowireCapeableBeanFactory.autowireBean(Object existingBean) AutowireCapeableBeanFactory.autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)

答案 4 :(得分:0)

我认为你不能用注释做到这一点,原因是你需要一个在运行时是动态的bean(可能是服务或B服务),所以在任何地方使用bean之前都会连接@Autowire 。一种解决方案是在需要时从上下文中获取bean。

    @Component
public class ServiceThatNeedsServiceInterface {


  ServiceInterface service;

  public void useService() {
     if(something is something){
        service = applicationContext.getBean("Abean", ServiceInterface.class);
     }else{
        service = applicationContext.getBean("Bbean", ServiceInterface.class);
     }
    service.someMethod();
  }
}

你可以把别的逻辑放在类中的某个地方作为一个单独的函数:

public void useService() {
        service = findService();
        service.someMethod();
      }

public ServiceInterface findService() {
         if(something is something){
            return applicationContext.getBean("Abean", ServiceInterface.class);
         }else{
            return applicationContext.getBean("Bbean", ServiceInterface.class);
         }

      }

这是动态的,这可能就是你想要的。

答案 5 :(得分:0)

您可以将@Qualifier注释与别名结合使用。查看基于属性here如何使用它加载bean的示例。您可以修改此方法并更改requestcontext中的属性/别名...