Bean 定义未从 Spring applicationContext.xml 文件加载

问题描述 投票:0回答:1
java spring spring-boot applicationcontext
1个回答
0
投票

通过

@Qualifier("queries")
,我能够“连接”所描述的(xml+)地图......就像这样:

package com.example.demo;

import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class Demo {
    public static void main(String[] args) {
        SpringApplication.run(Demo.class, args);
    }

    @Bean
    InitializingBean hello(/*@Autowired*/ @Qualifier("queries") Map<String, String> queries) {
        return () -> System.err.println(queries);
    }
}

...没有强有力的论据,为什么它不应该在任何 Bean/Repository/Service 中工作。

不过,我无法这么快地重现错误:省略限定符至少会填充(以某种方式在默认快速入门中)一个地图。


要重现“应用程序启动失败”,我们可以使用:

@Bean
InitializingBean hello2(Map x) {
  return () -> System.err.println(x);
}

,其中也不是:

  • (参数)名称符合条件
  • (或)声明泛型类型参数。

它为我们提供了(在 spring-boot 快速入门中):

...
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method hello2 in com.example.demo.Demo required a single bean, but 5 were found:
        - queries: defined in unknown location
        - systemProperties: a programmatically registered singleton
        - systemEnvironment: a programmatically registered singleton
        - contextParameters: a programmatically registered singleton
        - contextAttributes: a programmatically registered singleton

@价值替代品

这也是可能的:

//..somewhere in a spring bean (aware of applicationContext.xml)...
@Value("#{queries}") Map<String, String> queries;

...

(org.springframework...)@Value
+ SpEL 表示“‘查询’ bean”+ 匹配字段/参数。

© www.soinside.com 2019 - 2024. All rights reserved.