-1

I am new to Spring. I am testing @Inject annotation. For that I have created a logic:

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);
          }
        }

But this fails with an error saying:

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

Please help. I know I have done some trivial mistake.

Rajat Mishra
  • 364
  • 1
  • 5
  • 19

1 Answers1

0

You initialized your context with only one class:

new AnnotationConfigApplicationContext(config1.class)

You need to tell Spring to use second class.

You can add second class:

new AnnotationConfigApplicationContext(config1.class, config2.class)

Or add import in config1.

@Import({config2.class})