If Spring bean configured with JavaConfig, it BeanDefinition can not resolve BeanClassName, and return null. Same with xml or annotation config work well. What's the problem? How to fix?
Example code with trouble for Spring Boot, only add imports:
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());
}
}
I've faced the same problem while watching a Spring workshop on the YouTube, which used XML-based configuration. Of course, my solution is not production ready 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 of configuration class using stereotype annotation, everything would work fine:
@Configuration
@ComponentScan(value = "foo.bar")
public class Config {}
and
package foo.bar.model.impl
@Component
class FooImpl implements Foo {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With