微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 为什么@Autowired(required = false)不适用于@Configuration bean?

让我们举个例子说明一下:

有这个bean:

public class Foo {
    private String name;

    Foo(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

而这项服务:

public class FooService {
    private Foo foo;

    FooService(Foo foo) {
        this.foo = foo;
    }

    Foo getFoo() {
        return this.foo;
    }
}

鉴于以下Spring配置:

@Configuration
public class SpringContext {
//    @Bean
//    Foo foo() {
//        return new Foo("foo");
//    }

    @Bean
    @Autowired(required = false)
    FooService fooService(Foo foo) {
        if (foo == null) {
            return new FooService(new Foo("foo"));
        }
        return new FooService(foo);
    }
}

为了完整起见,这是一个简单的单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringContext.class})
public class SpringAppTests {
    @Autowired
    private FooService fooService;

    @Test
    public void testGetName() {
        Assert.assertEquals("foo",fooService.getFoo().getName());
    }
}

然后加载上下文将抛出NoSuchBeanDeFinitionException(Foo).

任何人都可以在这个例子中看到任何错误/缺失,或者为我提供理由吗?

谢谢!基督教

最佳答案
除了其他答案:

问题是spring在注入参数时没有考虑required = false.见ConstructorResolver

return this.beanfactory.resolveDependency(
        new DependencyDescriptor(param,true),beanName,autowiredBeanNames,typeConverter);

第二个参数总是如此:

public DependencyDescriptor(MethodParameter methodParameter,boolean required)

编辑:Spring使用ConstructorResolver

>“真正的”构造注入

@Autowired(required=false) // required=false WILL NOT WORK
public FooService(Foo foo){
    ...
}

>工厂方法

@Bean
@Autowired(required=false) // required=false WILL NOT WORK
FooService fooService(Foo foo) {
     if (foo == null) {
         return new FooService(new Foo("foo"));
     }
     return new FooService(foo);
}

因此,在这两种情况下都会忽略必需的属性.

原文地址:https://www.jb51.cc/spring/431751.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐