I am using Flyway 5.0.5 and I am unable to create a java (SpringJdbcMigration) with autowired properties... They end up null
.
The closest thing I can find is this question: Spring beans are not injected in flyway java based migration
The answer mentions it being fixed in Flyway 5 but the links are dead.
What am I missing?
I struggled with this for a long time due to my JPA dependency. I am going to edit the title of my question slightly to reflect this...
@Autowired
beans are instantiated from theApplicationContext
. We can create a different bean that isApplicationContextAware
and use that to "manually wire" our beans for use in migrations.A quite clean approach can be found here. Unfortunately, this throws an uncaught exception (specifically,
ApplicationContext
is null) when using JPA. Luckily, we can solve this by using the@DependsOn
annotation and force flyway to run after theApplicationContext
has been set.First we'll need the
SpringUtility
fromavehlies/spring-beans-flyway2
above.Then, configure a
flywayInitializer
with a@DependsOn
forspringUtility
. I extended theFlywayAutoConfiguration
here hoping to keep the autoconfiguration functionality. This mostly seems to have worked for me, except that turning off flyway in my gradle.build file no longer works, so I had to add the@Profile("!integration")
to prevent it from running during my tests. Other than that the autoconfiguration seems to work for me but admittedly I've only run one migration. Hopefully someone will correct me if I am wrong.And just to complete the example, here is a migration:
Thanks to avehlies on github, Andy Wilkinson on stack overflow and OldIMP on github for helping me along the way.
In case you are using more recent versions of Flyway, then extend
BaseJavaMigration
instead ofBaseSpringJdbcMigration
as the later is deprecated. Also, take a look at the below two comments by the user Wim Deblauwe.If you are using deltaspike you can use BeanProvider to get a reference to your DAO.
Change your DAO code:
Then in your migration method:
And there you've got your reference.
(referenced from: Flyway Migration with java)
The functionality hasn't made it into Flyway yet. It's being tracked by this issue. At the time of writing that issue is open and assigned to the 5.1.0 milestone.