java - 通过 Spring 注入(inject)空 map

标签 java spring dependency-injection

在我的@Configuration 文件中,我的 bean 具有类似于以下的关系:

@Bean
public Cache<Foo,Bar> fooBarCache(Map<Foo,Future<Bar>> refreshTaskMap) {
    return new AsyncUpdateCache(refreshTaskMap);
}

@Bean
public Map<Foo,Future<Bar>> refreshTaskMap() {
    return new HashMap<Foo,Future<Bar>>();
}

但是,ApplicationContext 加载失败,因为它提示“没有符合条件的 [com.example.Bar] 类型的 bean”。据我所知,Spring 试图为我创建一个 map 并假设我打算使用该 map 查找 bean 或类似的东西。

我如何防止它尝试执行其集合注入(inject)“魔法”并按照我声明的方式注入(inject) bean?我尝试在 fooBarCache 参数上添加 @Qualifier 注释,但这似乎没有帮助。

最佳答案

您可以使用另一种方法进行 bean 依赖项注入(inject) - 调用 bean 工厂方法而不是将其作为参数 (Spring doc)。那么您的配置将如下所示:

@Bean
public Cache<Foo,Bar> fooBarCache() {
    return new AsyncUpdateCache(refreshTaskMap()); // call the method
}

@Bean
public Map<Foo,Future<Bar>> refreshTaskMap() {
    return new HashMap<Foo,Future<Bar>>();
}

Spring 足够聪明,可以意识到您要使用bean refreshTaskMap而不是简单地调用该方法,而不是创建一个新的和非托管的 map 实例,它会将调用替换为对现有 refreshTaskMap 的查找。 bean 。进一步描述 here .

如果您打算 Autowiring refreshTaskMap在其他 bean 中(在此配置类之外),@Autowire Map<String, V> 的 Springs 语义是 Autowiring V 类型的所有 bean 的映射,其中键是 bean 名称(映射键类型必须是 String )( reference )

Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names

在这种情况下,you should use @Resource :

beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.

关于java - 通过 Spring 注入(inject)空 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34407569/

相关文章:

java - 在 spring jdbctemplate 中传递不带单引号的字符串

java - spring hibernate项目的初始化导致错误

symfony - 选择众多服务之一作为要使用的服务

c# - 如何在asp.net core 2.2中注册IFileProvider进行依赖注入(inject)?

c# - 使用简单注入(inject)器 3.1.2 注册 IUserStore

java - 如何将光标移至 JScrollPane 内 JTextArea 的顶部

java - 线程的问题

java - 扫描嵌入式 Tomcat 中的 list 类路径 jar

java - RestTemplate x Feign Client 有什么区别?

java - 无法导入 org.apache.commons.lang3.math.NumberUtils