How to build a Spring Boot application with REST and AngularJS

This article shows how to build a Sprint Boot application with REST endpoint and AngularJS frontend. Spring Boot makes it easy to create stand-alone Spring-based applications that you can ‘just run’. It uses a ‘convention over configuration’ approach to get you up and running in no-time, while offering all Spring features that you have grown fond of in the past years.

Key features:

  • Creates stand-alone Spring applications
  • Embed web server directly (no WAR files). No separate web server needed.
  • Automatic Spring configuration wherever possible
  • No code generation and no XML configuration

Advantages:

  • Embed web server directly (no WAR files). No separate web server needed.
  • Better debugging in IDEs
  • Faster deployments (about 50%)
  • No web.xml or configurations needed. You can be up and running with two java files and a pom file.

Disadvantages:

  • Custom configuration will be a bit of a puzzle
  • Migrating your legacy Spring project

We will create a REST web service application using Spring Boot and a client application using AngularJS. REST web service will expose methods for create, read, update and delete (CRUD) operation. The Angular application will use Angular Http API for CRUD operation. It uses by default the TomEE embedded server.

Step 1: Generate a new Spring Boot project

The first step is to generate a new Spring Boot project at https://start.spring.io. I’ve used the values in the screenshot below. Of course, you can use your own group and artifact ids. We need JPA for persistence. DevTools is handy for doing hot deploys. H2 is an in-memory database. So, we can create, edit and delete entities in memory.

Spring Ini

Download the zipped Project file. Extract it to and open the project.

Step 2: Modify the pom file

Add the spring-boot-starter-data-rest dependency to the pom.xml file.


<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-rest</artifactId>

</dependency>


Your final pom.xml file should look like this:


<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.pancompany</groupId> <artifactId>users</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>users</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

Step 3: Create a database entity

Create an entity. This is basically a Java class called User. Make sure you annocate the class with @Entity.


@Entity

public class User {

 

    @Id

    @GeneratedValue

    private Long id;

    private String name;

    private Integer age;

    private double salary;

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public Integer getAge() {

        return age;

    }

 

    public void setAge(Integer age) {

        this.age = age;

    }

 

    public double getSalary() {

        return salary;

    }

 

    public void setSalary(double salary) {

        this.salary = salary;

    }

}



Step 4: Create a JPA repository

Create a JPA repository called UserRespository. It is advisable to make it an interface that implements the JPARepository so that it implements all basic database methods like ‘findAll’, ‘delete’, ‘save’, etc. The first argument represents the object we will save: ‘User’ and the secodargument is the type of the id field: Long.


@Repository

public interface UserRepository extends JpaRepository<User, Long> {

}



Step 5: Create a Rest Controller

Create and run unit tests to ensure the code is working. Annotate the test as follows:


@RunWith(SpringRunner.class)

@SpringBootTest



Step 6: Create a Rest Controller

Create a Rest Controller called UserController and annotate it with @RestController. Annotate it with the RequestMapping where the url will be called. Autowire the UserRepository so we can make database calls.


@RestController

@RequestMapping("/rest/user")

public class UserController {

 

    @Autowired

    private UserRepository userRepository;

 

    @GetMapping

    public List<User> listUsers(){

        return userRepository.findAll();

    }

 

    @PostMapping

    public void addUser(@RequestBody User user){

        userRepository.save(user);

    }

 

    @DeleteMapping

    public void deleteUser(@RequestParam Long userId){

        userRepository.delete(userId);

    }

 

    @PutMapping

    public void updateUser(@RequestBody User user){

        userRepository.save(user);

    }

}



Step 7: Add the AngularJS frontend

Create a folder called static under /src/main/resources. It will be served by the web server and will hold static properties. Install angularjs in static folder by running the following command:

npm install angular@1.6.3

Create the app.js and index.html files. Put both files in the static folder.

Step 8: Build and Run the application

Run the following command to compile the application, start Spring Boot   and run the application

mvn spring-boot:run

Go to a browser at http://localhost:8080.

Add a user, edit it and delete it. The application works.

Open the network tab of the web browser and check the HTTP and REST communication.

The following HTTP URLs and Methods for CRUD Operation are used:

CRUD 

Step 9: End result

For further reference check THESE source files on GITHUB.

naar overzicht

Wilt u reageren of meer weten?

Heeft u iets in dit artikel gelezen dat uw interesse gewekt heeft? Laat het ons weten!

Deze post delen?

Trotse winnaar van een
FD Gazellen Award
2014, 2015, 2016 en 2017

© 2018 | Europalaan 12a | 5232BC 's-Hertogenbosch | T: +31 (0)85 0290550 | E: info@pancompany.com