Java Spring嵌套bean

时间:2018-10-26 17:47:04

标签: java spring autowired

创建了myLoaders bean并自动装配。该代码之后调用内部调用h()函数的load。当调用h()函数时,选中了aa1,并且两者都以null的形式出现。

虽然a和a1已通过自动接线,但不确定为什么会以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();
    }


}

有人可以检查。如果您可以提供一些参考,那将真的很有帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

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

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