加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:38:57 所属栏目:大数据 来源:网络整理
导读:让我们举个例子说明一下: 有这个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)

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

有这个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);
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读