Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring, JavaConfig, BeanDefinition and empty getBeanClassName

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());
    }
}
like image 286
Barlog Avatar asked Oct 31 '22 14:10

Barlog


1 Answers

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 {...}
like image 62
xuesheng Save Ukraine Avatar answered Nov 09 '22 15:11

xuesheng Save Ukraine