Running Spring Boot with Angular
A current trend among Java developers is to move the user interface entirely to the browser. Using Angular framework on the front end is one of the most popular ways to achieve this.
This post will help Java developers integrate their Spring boot applications with Angular 4.
Let’s create a bootstrapped application using Spring Initializr.
If you open your newly generated project in your IDE you should have the following project structure:
Edit SpringBootAnglularApplication.Java to the following:
To test the application just edit the SpringBootAngularApplicationTests.Java and run it.
Now let’s move to the front end side.
The Angular CLI is a command line interface tool that can create Angular projects.
You may install it from here if you haven’t yet!
Now lets create a new Angular app in the project’s root folder:
To test integration with the Backend let’s make some small modifications under front-end/‘src/app’:
Edit app.component.ts file:
Edit app.component.html file
Here the ‘sayHello()’ function will be triggered by the button to call the Rest endpoint.
Add HttpModule in app.module.ts file:
By default transpiled static web content is placed in the ‘dist’ folder.
Let’s map it to Spring boot’s resources/static.
Go to the ‘front-end’ folder and change ‘outDir’ parameter in ‘angular.cli’ file.
This way the generated static web content will be placed where Spring expects it to be.
To run the ‘front-end’ build process every time we build our Spring Boot application modify the build.gradle file.
‘Moowork plugin’ is used here to create ‘buildAngular’ task.
Finally let’s build a ‘fat’ jar and execute it:
Now If you go to http://localhost:8080 in your browser you should see the following:
Mustafa Eldar is a full-stack software engineer at Speed & Function with a focus in Java.Read more