2017-06-19 77 views
-1

我是Spring的新手。我正在測試@Inject註釋。對於我創建了一個邏輯:注入自動佈線依賴關係失敗,java配置

import javax.inject.Inject; 

    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.annotation.AnnotationConfigApplicationContext; 
    import org.springframework.context.annotation.Bean; 
    import org.springframework.context.annotation.Configuration; 

     class A { 
      int a; 

      public A(int a) { 
      this.a = a; 
      } 
     } 

     class B { 
      A x; 

      public B(A x) { 
      this.x = x; 
      } 
     } 

     @Configuration 
     class config1 { 
      A a; 

      @Inject 
      public void setA(A a) { 
      this.a = a; 
      } 

      @Bean 
      public B getB() { 
      return new B(a); 
      } 
     } 

     @Configuration 
     class config2 { 
      @Bean 
      public A getA() { 
      return new A(4); 
      } 
     } 

     public class Testt { 
      public static void main(String[] args) { 
      ApplicationContext ctx = new AnnotationConfigApplicationContext(config1.class); 
      B oa = ctx.getBean(B.class); 
      System.out.println(oa.x.a); 
      } 
     } 

但這種失敗,錯誤說:

Error creating bean with name 'config1': Injection of autowired dependencies failed; 

請幫助。我知道我犯了一些小錯誤。

+0

請分享完整的例外或stacktrace,它可能會有所幫助。 –

+0

你想在這裏做什麼? –

回答

0

你只有一個類初始化您的上下文:

new AnnotationConfigApplicationContext(config1.class) 

你需要告訴Spring使用第二類。

,您可以添加第二類:

new AnnotationConfigApplicationContext(config1.class, config2.class) 

還是在CONFIG1增加進口。

@Import({config2.class}) 
相關問題