Spring,JavaConfig,BeanDefinition和空的getBeanClassName

时间:2014-11-10 20:05:30

标签: java spring spring-boot

如果Spring bean配置了JavaConfig,那么BeanDefinition无法解析BeanClassName,并返回null。 与xml或annotation配置相同。 问题是什么?怎么解决?

Spring Boot出现问题的示例代码,只添加导入:

interface Foo {}

class FooImpl implements Foo {}

@ComponentScan
@EnableAutoConfiguration
@Configuration
public class App implements CommandLineRunner {
    public static void main(String... args) {
        SpringApplication.run(App.class, args);
    }

    @Bean(name = "foo")
    Foo getFoo() { return new FooImpl(); }

    @Autowired
    private ConfigurableListableBeanFactory factory;

    @Override
    public void run(String... args) {
        BeanDefinition definition = factory.getBeanDefinition("foo");
        System.out.println(definition.getBeanClassName());
    }
}

1 个答案:

答案 0 :(得分:2)

我在观看YouTube上使用基于XML的配置的春季研讨会时遇到了同样的问题。当然,我的解决方案不是生产就绪,看起来像黑客,但它解决了我的问题:

BeanDefinition beanDefinition;
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) bd;
StandardMethodMetadata factoryMethodMetadata = (StandardMethodMetadata) annotatedBeanDefinition.getFactoryMethodMetadata();
Class<?> originalClass = factoryMethodMetadata.getIntrospectedMethod().getReturnType();

修改1 事实证明,如果使用构造型注释在配置类之外定义bean,一切都可以正常工作:

@Configuration
@ComponentScan(value = "foo.bar")
public class Config {}

package foo.bar.model.impl

@Component
class FooImpl implements Foo {...}