0

I have configured my Spring application as below:

Class A{

  @Resource
  private B objB;
  @Resource
  private C objC;

}

Class B{}
Class C{}

@Configuration
Class SpringConfigs{
  @Bean
  public A objA(){
      return new A();
  }

  @Bean
  public B objB(){
      return new B();
  }

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

I use component-scan to pick the @Configurations. My question is will Spring inject the Beans for B & C while creating the bean for A. I use @Resource inside the Class A but use new operator to create the Bean, so will Spring recognize the annotations inside Class A and inject them? Thanks.

broun
  • 2,483
  • 5
  • 40
  • 55

1 Answers1

0

Your application is going to run just fine. Have you tried?

When your SpringConfigs configuration class is picked up by class path scanning, the @Bean annotated methods will be processed to create the relevant beans.

You are probably referring to an common beginner mistake that consists of creating the bean by hand and expect Spring to realize it has to do something (such as wiring dependencies or create a proxy to provide other features).

You are indeed creating the bean yourself but you are doing it within a method that the BeanFactory is going to invoke to retrieve the bean instance. Once the instance is added to the factory, it is going to be post-processed just like any other bean (i.e. such as the ones created through xml config)

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89
  • No Im not referring to the "creating bean by hand" thing. Yes i ran the application and got NPE for the beans that were autowired to the other bean. Possible that I might be missing something will take a closer look and update. Thanks for the response. – broun Jul 13 '14 at 08:17