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;
}
}
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);
}
}
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());
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With