2011-06-03 95 views
8

在Guice 2或3中,存在所謂的輔助/部分注入描述here.由此,Guice爲我的對象綜合了工廠實現(實現我的接口),並且一些構造器參數由Guice注入,並且一些從上下文。春季輔助注射是否可行?

是否有可能以及如何用Spring做同樣的事情?

+1

這個問題還算舊。春天有什麼變化嗎?這聽起來像是一個合理的功能請求(不是嗎?) – theadam 2013-09-23 16:19:18

回答

7

以下是我所要求的。雖然它沒有綜合工廠的實施,但是工廠有權訪問注入環境,因此在施工期間可以使用其他(可注射的工件)。它使用基於java的@Configuration而不是XML,但它也可以用於XML。

工廠接口:

public interface Robot { 

} 

// Implementation of this is to be injected by the IoC in the Robot instances 
public interface Brain { 
    String think(); 
} 

public class RobotImpl implements Robot { 

    private final String name_; 
    private final Brain brain_; 

    @Inject 
    public RobotImpl(String name, Brain brain) { 
     name_ = name; 
     brain_ = brain; 
    } 

    public String toString() { 
     return "RobotImpl [name_=" + name_ + "] thinks about " + brain_.think(); 
    } 
} 

public class RobotBrain implements Brain { 
    public String think() { 
     return "an idea"; 
    } 
} 


// The assisted factory type 
public interface RobotFactory { 
    Robot newRobot(String name); 
} 

//這是示出了如何執行輔助注射Spring配置

@Configuration 
class RobotConfig { 

    @Bean @Scope(SCOPE_PROTOTYPE) 
    public RobotFactory robotFactory() { 
     return new RobotFactory() { 

      @Override 
      public Robot newRobot(String name) { 
       return new RobotImpl(name, r2dxBrain()); 
      } 
     }; 
    } 

    @Bean @Scope(SCOPE_PROTOTYPE) 
    public Brain r2dxBrain() { 
     return new RobotBrain(); 
    } 
} 

測試代碼:

public class RobotTest { 

    @Test 
    public void t1() throws Exception { 
     ApplicationContext ctx = new 
          AnnotationConfigApplicationContext(RobotConfig.class); 
     RobotFactory rf = ctx.getBean(RobotFactory.class); 
     assertThat(rf.newRobot("R2D2").toString(), 
      equalTo("RobotImpl [name_=R2D2] thins about an idea")); 
    } 

} 

這實現了Guice的功能。棘手的區別是Scope。 Spring的默認範圍是Singleton而Guice's不是(它是原型)。

4

AFAIK你不能。在春季你可以有Instantiation using a static factory methodInstantiation using an instance factory method。通過第二個選項,您可以定義一個作爲另一個bean的工廠的bean myFactoryBean。您也可以通過使用constructor-arg(請參閱Using An Instance Factory Method on this blog部分)將構造參數傳遞給myFactoryBean,它可以使您等價於Guice注入的參數。但是,我不知道在調用工廠方法時從上下文提供更多參數的方法。

+1

我認爲你可以在Spring-EL中使用3.0,但它開始感覺非常噁心。 – 2011-06-03 09:41:48