Bar*_*log 5 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());
}
}
Run Code Online (Sandbox Code Playgroud)
我在 YouTube 上观看 Spring 研讨会时遇到了同样的问题,该研讨会使用基于 XML 的配置。当然,我的解决方案还没有准备好投入生产,看起来像是一个黑客,但它解决了我的问题:
BeanDefinition beanDefinition;
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) bd;
StandardMethodMetadata factoryMethodMetadata = (StandardMethodMetadata) annotatedBeanDefinition.getFactoryMethodMetadata();
Class<?> originalClass = factoryMethodMetadata.getIntrospectedMethod().getReturnType();
Run Code Online (Sandbox Code Playgroud)
编辑 1 事实证明,如果您使用构造型注释在配置类之外定义 bean,则一切都会正常工作:
@Configuration
@ComponentScan(value = "foo.bar")
public class Config {}
Run Code Online (Sandbox Code Playgroud)
和
package foo.bar.model.impl
@Component
class FooImpl implements Foo {...}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
304 次 |
最近记录: |