将Spring Boot bean注入bean注入方法 [英] Spring boot bean into bean injection methodology

查看:96
本文介绍了将Spring Boot bean注入bean注入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我这两个Spring Boot应用程序类之间是否有区别(就Spring bean注入和尊重单例条件或任何其他Spring Boot魔术而言)?

Can anyone tell me if there is a difference (in terms of spring bean injection and respecting singleton conditions or any other spring boot magic) in these two spring boot application classes?

@Bean
@Scope("singleton")
public UserService userService(Foo foo){
    return new UserService(foo);
}

@Bean
@Scope("singleton")
public Foo foo(){
    return new Foo();
}

并调用未声明 Foo 作为方法参数在 userService()上,而是通过直接方法调用 foo()

AND calling not declaring Foo as a method parameter on userService() but rather injecting it via a direct method call to foo()

@Bean
@Scope("singleton")
public UserService userService(){
    return new UserService(foo());
}

@Bean
@Scope("singleton")
public Foo foo(){
    return new Foo();
}


推荐答案

不,没有区别。有人可能会认为,每次在该配置类中调用 foo()时,您都会得到一个新的bean实例,但是Spring在这种情况下的工作方式是,它为拦截所有方法调用的配置类。然后,代理检查是否已经存在类型为 Foo 的Bean,如果是,它将返回现有实例,否则将方法调用委托给实现,然后将新的Bean委托给实现。

No, there is no difference. One might think, you would get a new bean instance everytime you call foo() in that configuration class, but the way Spring works in that case is, it creates a proxy for that configuration class which intercepts all method calls. The proxy then checks, if there is already a bean of type Foo, if so it returns the existing instance, otherwise the method call is delegated to the implementation and a new bean is created.

明智的代码样式,但是,我认为在您的第一个示例中,对 Foo bean的依赖性更大明显比第二个示例中标记。

Code style wise, however, i think in your first example the dependency to the Foo bean is more clearly marked than in the second example.

这篇关于将Spring Boot bean注入bean注入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆