Integrating an Angular project with Spring Boot

Majd Asab
3 min readJul 28, 2018

--

Spring Boot + Angular

It’s been a while since I’ve written any posts, and one of the latest challenges I faced was figuring out how to integrate an Angular project with a Spring Boot project.
Step 1: setup your Spring Boot application
Go ahead and initialize your Spring boot application anyway you like. I personally find https://start.spring.io/ a convenient way to get started, so I’m going to go ahead and generate a Maven Spring Boot application, with a Web dependency.

Screenshot from https://start.spring.io/ showing Spring Boot project specifications.

When you’re all setup and ready, open the project with your favorite IDE. Your directory structure should look something like this:

Screenshot of the project inside the IDE with the main and resources directories highlighted

Let’s setup a restcontroller quickly and get a response back from the web server to make sure everything is working fine:

A screenshot of modification of the code in SpringBootWithAnglarApplication class

if we run it and navigate to http://localhost:8080 this should be the result:

A screenshot of the of the web browser

If everything works fine, go back to the class RestController class and remove the following code:

@RequestMapping("/")
public String greet(){
return "welcome!";
}

Step 2: setup your Angular application

Start by creating a new directory called frontend (under resources), and navigate in your terminal to it src/main/resources/frontend/

Run the command ng new angular-app to create a new angular project within our Spring Boot project. Your project structure should look like this:

Screenshot of the Angular project structure within Spring Boot

Now we need to change the configuration in such a way that Angular can build it’s files and provides them for Spring Boot to use. To do that we must edit the angular.json file and change the outputPath value to generate the build files in src/main/resources/public/ directory of the project.

Screenshot of the modified angular.json

In order to inform Maven that the Angular project needs to be compiled first before the Spring Boot files we need to inset a plugin into the pom.xml file:

Screenshot of the added plugin to the pom.xml file

Step 3: package your project

From the root of the project, type mvn package. Maven will now build the Angular project and place the files in the public directory.

Done:

Now go ahead and run your jar using java -jar target/name-of-jar.jar and navigate to http://localhost:8080, you should see the the default Angular project index.html:

Screenshot of localhost:8080

Optional:

If you don’t want to keep the Angular project embedded within the Spring Boot project, once you package the Spring Boot project and generated the required files to the public directory, go ahead and remove the Angular project from the resources directory, and remove the plugin from the pom file.

--

--