gpt4 book ai didi

java - Spring getBeanNamesForType 工作不正常

转载 作者:行者123 更新时间:2023-12-03 19:10:16 25 4
gpt4 key购买 nike

我有简单的上下文配置

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ResolvableType;

import java.util.Arrays;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);

String[] namesForType = ctx.getBeanNamesForType(ResolvableType.forClassWithGenerics(Transformer.class, Integer.class, String.class));

System.out.println("namesForType = " + Arrays.toString(namesForType));
}

@Bean
public Transformer<Integer, String> stringTransformer() {
return new Transformer<Integer, String>();
}
}

和简单的类
package com.example;

public class Transformer<F, T> {

T transform(F from) {
return null;
}
}

当我启动应用程序时,输出是 namesForType = []

如果将 bean 的创建更改为单独的类,例如
    @Bean
public Transformer<Integer, String> stringTransformer() {
return new Transformer<Integer, String>(){};
}

输出为 namesForType = [stringTransformer]

最佳答案

这是正确的行为。在使用 @Bean 注释之前,它不会在 spring 上下文中被拾取。

关于java - Spring getBeanNamesForType 工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39465047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com