Sunday, October 9, 2022

Auto-Reload Spring MVC Project

This is a much-required process while we develop spring boot applications. We do changes continuously and want to see the result at the same time without manually rebuilding the application. 

For the changes in Java files, we need to include a dependency 

developmentOnly 'org.springframework.boot:spring-boot-devtools'


In Eclipse, this should be enough, I have not tested it though.

If you are using IntelliJ, we need to do one extra step to enable hot-reload.





You need to go to settings (CTRL+ALT+S) and click "Build, Execution, Deployment" select "Compiler", and then on the right side, select the select "Build project automatically".


So far, we have implemented the hot reload of Java files. 

This does not take care of the changes in other files, for example, changes in template files, or other resources files. There are many alternatives to implement this, I prefer using gulp which watches the changes in the resource files and transfers the changes files into the build directory.  

(Reference:https: //attacomsian.com/blog/spring-boot-auto-reload-thymeleaf-templates )

1) Your system should have the latest npm and node. 
2) Instal gulp-client 
npm install gulp-cli -g
Installing globally makes it available to all other applications too.
3) Create a file package.json in the root folder with the following content

{
"name": "Corona Tracker",
"scripts": {
"gulp-watch": "gulp-watch"
},
"dependencies": {
"gulp": "^4.0.2",
"gulp-watch": "^5.0.1"
}
}


4) Run the command npm install (which installs these packages) 
5) Now, we have to define the actual task of watching and taking action. For that, create a file called "gulpfile.js" with the following text:

var gulp =require('gulp'),
watch=require('gulp-watch');

gulp.task('watch',function(){
return watch('src/main/resources/templates/**/*.*',()=>{
gulp.src('src/main/resources/templates/**')
.pipe(gulp.dest('build/resources/main/templates/'));
});
});

The task defined here is "watch"

6) Run "gulp watch" which watches directory templates, and if any changes are there, it copies the changes into the build directory. 


I preferred this method of loading static file changes because it is fast and fully customizable. The method in IntelliJ did not work in my case. (Changing IntelliJ registry did not sound good to me) 

No comments:

Post a Comment