【问题标题】:how do we load particular class dynamically using dependency injection in spring?我们如何在spring中使用依赖注入动态加载特定类?
【发布时间】:2016-02-19 19:20:35
【问题描述】:
我们如何在 spring 中使用依赖注入动态加载特定的类?
【问题讨论】:
-
Tom 是对的,但是您应该先查看 Spring 文档 (spring.io/docs)。这绝对是我见过的最好的之一。总是试着先在那里找到你的答案,然后再问 SO :)
-
标签:
java
spring
spring-mvc
dependency-injection
【解决方案1】:
您可以使用以下名称创建@Bean:
@Bean(name={"airtel"})
public Operator getOperator1() {
return new Airtel();
}
@Bean(name={"idea"})
public Operator getOperator2() {
return new Idea();
}
并使用@Qualifier 自动装配它们
@Autowired
@Qualifier("airtel")
private Operator airtel;
@Autowired
@Qualifier("idea")
private Operator idea;
【解决方案2】:
虽然汤姆·塞巴斯蒂安的回答是正确的,但它可以改进(我在评论区中没有空间来解释改进)。
使用@Bean 时的约定是在方法名称中省略“get”。这是因为configuration classes use a method's name as the bean name。在您的 @Configuration-annotated 类中声明 bean,如下所示:
@Bean
public Operator airtel()
{
return new Airtel();
}
@Bean
public Operator idea()
{
return new Idea();
}
要注入您的 bean,请使用 @Resource,而不是 Spring reference doc 中推荐的 @Autowired:
如果你打算用名字来表达注解驱动的注入,不要
主要使用@Autowired,即使在技术上能够
通过@Qualifier 值引用bean 名称。相反,使用
JSR-250 @Resource 注解...
@Resource(name="airtel")
private Operator airtel;
@Resource(name="idea")
private Operator idea;
事实证明这里不需要@Resource 的name...我将它包含在上面以演示它是如何使用的。如果字段的名称与 bean 的名称相同(在此示例中为 @Configuration-annotated 类中的方法名称),则不需要 name:
@Resource
private Operator airtel;
@Resource
private Operator idea;
正如我所说,汤姆的回答是正确的;我想用更高级的细节稍微扩展它。