Spring, JavaConfig, BeanDefinition, and an empty getBeanClassName

If the Spring bean configured with JavaConfig, the BeanDefinition cannot resolve the BeanClassName and return null. The same with xml or annotation configuration works well. What is the problem? How to fix?

Sample code with a problem for Spring Loading, adding only import:

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()); } } 
+5
source share
1 answer

I ran into the same issue when watching Spring's YouTube seminar that used XML-based configuration. Of course, my solution is not ready for production and looks like a hack, but it solved my problem:

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

Edit 1 It turns out that if you define your bean outside the configuration class using the stereotype annotation, everything will work fine:

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

and

 package foo.bar.model.impl @Component class FooImpl implements Foo {...} 
+2
source

Source: https://habr.com/ru/post/1206585/


All Articles