When doing debugging with break points, I noticed that the order of execution of the @Bean annotated methods is not really related to their dependency relation. For e.g:
@Configuration
public class config {
@Bean (name = "myDataSource")
public DataSource dataSource() {return new HikariDataSource();}
@Bean
public TransactionManager transactionManager(@Qualifier("myDataSource") DataSource dataSource) {
return new TransactionManager(dataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {...}
}
The transactionManager or sqlSessionFactory method always gets run before the dataSource() method in my app. I made sure there's no data source auto config or any other code that might have created another data source.
And the app behavior is correct, it can connect to the correct DB and retrieve data.
This odd behavior might have something to do with multiple datasources. I configured more than 1 datasource in my app.
I know Spring has similar mechanism when dealing with cyclic dependencies. Say class A and B depends on each other, and when creating Bean A, A.b will be set to an empty instance of B. The same goes for B.
Here I'm assuming when running method sqlSessionFactory(), an empty dataSource will be created and passed to it. And that dataSource will later reference/proxy bean "myDataSource".
I want to know if my assumption is correct or if someone can explain the behavior clearly.
Edit
This is what my debug point looks like:

So the transactionManager() method always gets run first. And at this time, the injected dataSource (HikariDataSource) is still null.
But after the app starts and makes DB queries, it's using the correct dataSource:
My another dataSource is called orderDataSource and the mapper is referring it correctly.
I mean at last the transactionManger and sqlSessionFactory do use my specified dataSources, satisfying what my annotation demands, otherwise it would be a Spring bug and the app won't be able to function. But when the main thread is initializing those beans, the dataSource() method gets run last. I find it out in debugging mode. I'm trying to understand the underlying mechanism here.


