Spring injection bind toInstance
Is there a way to bind an injected object to a specific instance using Spring DI similar to Google Guice's
bind(MyClass.class).toInstance(myclassobject);
开发者_JAVA百科
If the constructor or member variable is annotated with @Autowired
, Spring will try to find a bean that matches the type of the Object. You can get similar functionality to the annotation using @Qualifier
, for example:
bind(MyClass.class).annotatedWith(Names.named("main")).toInstance(myclassobject);
would become in Spring:
@Autowired @Qualifier("main") private MyClass myClassObject;
<bean name="myClassObject" class="example.MyClassImpl">
<qualifier value="main"/>
</bean>
See http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation for more.
精彩评论