gpt4 book ai didi

Java Spring 嵌套 bean

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:18 25 4
gpt4 key购买 nike

创建了 myLoaders bean 并 Autowiring 。在该代码调用loading之后,它在内部调用h()函数。当调用 h() 函数时,检查 aa1 并且两者都为 null

尽管 a 和 a1 已传递 Autowiring ,但不确定为什么它会显示为 null

package nestedbean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

@Autowired
Loaders myLoaders;

@Bean
public A a(){
return new A(b());
}

@Bean
public A1 a1(){
return new A1();
}

@Bean
public B b(){
return new B(c());
}

@Bean
public C c(){return new C();}

@Bean
public History history(){
return new History(a(), a1());
}

@Bean
public Loaders myLoaders() {
return new MyLoaders( history());
}
@Bean
public Void load () throws Exception {
myLoaders.loading();
return null ;
}

static class History{
A a ;
A1 a1 ;

@Autowired
public History(A a , A1 a1 ) {
a = a ; a1 = a1 ;
}
public void h(){ //when this function is called a and a1 both are null
a1.test();
}
}

static class MyLoaders implements Loaders {
public History h ;
@Autowired C c;

@Autowired
public MyLoaders(History history ){ h= history ;}
public void loading(){
System.out.println("loading");
h.h();

}
}


static class A {
B b;
public A(B b){ this.b = b ;}
}

static class A1 {
@Autowired
C c;

B b;
public void test(){
System.out.println("testing");
}
}
static class B{ C c;
public B(C c){ c = c ;}
}
static class C { }

public interface Loaders {
final String mystring = "4";
public void loading();
}


}

有人可以检查一下吗?如果您可以提供一些引用资料,那将非常有帮助。

谢谢

最佳答案

您的构造函数未设置字段,您忘记了关键字“this”来引用您的实例。尝试使用这个构造函数:

        @Autowired
public History(A a , A1 a1 ) {
this.a = a ; this.a1 = a1 ;
}

关于Java Spring 嵌套 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com