Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring inject a bean into another bean

I am trying to inject a bean into another bean that uses it. How can I do this?

public class MySpringConfig{
@Bean
public MyObject getMyObject() {
  //.....

  return MyObjectInstance;
}



@Bean
public SomeObject getSomeObject(MyObject myObject) {

  //.....

  return SomeObjectInstance;
 }    
}
like image 764
James Avatar asked Aug 12 '19 14:08

James


Video Answer


3 Answers

I think you can do this with this way, this is working in my project.

@Configuration
public class AppConfig {

 @Bean
 public Bean1 foo(@Qualifier("bean2") Bean2 bean2) {
  return new Bean1(bean2);
 }

}
like image 174
Negi Rox Avatar answered Oct 16 '22 10:10

Negi Rox


i think that might work!

 @Configuration
 public class AppConfig {

  @Bean
  public Bean2 bean2() {
      return new Bean2();
  }

  @Bean
  @DependsOn({"bean2"})
  public Bean1 foo(@Autowired Bean2 bean2) {
     return new Bean1(bean2); // or your can write new Bean1(bean2());
  }

}

like image 39
Ramin Manesh Avatar answered Oct 16 '22 12:10

Ramin Manesh


Parameters don't work exactly in the same way in @Bean and @Component.
For a class annotated with @Component, specifying them is required for the autowired constructor but in a @Bean declaration you don't need to provide a parameter to specify the MyObject dependency to use (while it will work) if that is accessible in the current class, which is your case.
So you want to inject directly the bean by invoking getMyObject() in the @Bean definition.
For example to pass it a constructor arg :

@Bean
public SomeObject getSomeObject() {

  //....
  // you injected MyObject in the current bean to create
  SomeObject object = new SomeObject(getMyObject());
  //...
  return SomeObjectInstance;     
}

And don't forget to annotate the class with @Configuration to make it considered by Spring.

like image 1
davidxxx Avatar answered Oct 16 '22 11:10

davidxxx