Spring injection bind toInstance

故事扮演 提交于 2019-12-12 12:42:01

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/6970920/spring-injection-bind-toinstance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!