I have Spring XML configuration file like this:
<bean id="A" class="a.b.c.d.ConfigurationA" />
<bean class="a.b.c.d.ConfigurationB" />
<bean id="C" class="a.b.c.d.e.ConfigurationC" depends-on="objectFromConfigurationB" />
Each configuration file import other config classes. Example:
@Configuration
@Import({ConfigA.class, ConfigB.class})
class ConfigurationA {
@Bean
public ABC abc() {
return new ABC();
}
...
...
..
}
I would like to rewrite this XML config into Java keeping all relations (depends-on
). How can I do it?
I tried with:
- ComponentScan
- Import
always the same: beans from inner configuration files are not loaded into spring context. I caught No bean 'A' available
error during startup.
How to create depends-on
relation during import configuration bundle?
CodePudding user response:
You are looking for @DependsOn
in your ConfigurationC
as follows: @DependsOn("name-of-bean-B")
.
CodePudding user response:
With component scanning you should not need to do anything.
@Component
class A {
}
@Component {
class B {
}
@Componet {
class C {
private final B b;
@Autowired
C(B b) {
this.b = b;
}
}
Using constructor injection in component C gets you exactly what you want, there is no need to do the depends on. If you are newer versions of spring you don't even need the @Autowired
on the constructor.
I converted a project with about 10 XML spring files into Java Configuration. I found that writing @Bean
definitions each one in an @Configuration class was not necessary, I thought it would cause bootup times to be faster but made no difference. Using component scanning is lot less code and makes things much simpler. If you are on spring boot you need to make sure that the packages that have code in them are being scanned, for example if you have library in com.example.lib
and the @SpringBootApplication
class is in com.example.app
then the beans in com.example.lib
won't be picked up because by default it will scan only the child packages of com.example.app
you will need to add more packages to scan to the config or move the main spring boot app class to com.example