Spring工厂有自定义构造函数

时间:2016-03-26 01:14:50

标签: java spring factory

我正在尝试使用Spring创建工厂模式。我可以使用FactoryBean创建它,如下所示:

服务接口

public interface MyService {
   void doProcess();
}

实现

 @Service(value = "fooMyService")
 @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
 public class FooMyServiceImpl implements MyService {

   @Override
   public void doProcess() {
     ...
   }

 }

@Service(value = "barMyService")
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BarMyServiceImpl implements MyService {

  @Override
  public void doProcess() {
    ...
  }

}

工厂

public interface MyServiceFactory {

  MyService getService(String serviceName);

}

出厂配置

@Bean
public FactoryBean<?> myServiceFactoryBean() {
  ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
  factoryBean.setServiceLocatorInterface(MyServiceFactory.class);
  return factoryBean;
}

因此,下面的代码调用服务

@Autowired
private MyServiceFactory myServiceFactory;  
...
MyService fooMyService = myServiceFactory.getService("fooMyService");
MyService barMyService = myServiceFactory.getService("barMyService");

我现在需要做的是创建一个带有自定义构造函数的工厂,它将在运行时创建并注入bean。

春天有可能吗?

0 个答案:

没有答案