Getting Started | Building an Application with Spring Boot
Build an application enterprise with Spring boot and Angular use Jpa
Objective:
The objective of this tutorial is how to know Design Patterns work. In this tutorial we will create an application enterprise to calculate the language and the level for the applications how many language used in the app like Java, Php, Javascript etc... Criticality like Low, Medium and High.
Java Design Patterns
1. Design Patterns are already defined and provides industry standard approach to solve a recurring problem, so it saves time if we sensibly use the design pattern. There are many java design patterns that we can use in our java based projects.
2. Using design patterns promotes reusability that leads to more robust and highly maintainable code. It helps in reducing total cost of ownership (TCO) of the software product.
3. Since design patterns are already defined, it makes our code easy to understand and debug. It leads to faster development and new members of team understand it easily.
Used Skills in this project:
Java, SpringBoot, MicroServices, REST WebServices, JPA, Hibernate, MySQL Database, Maven, Angular, GitHub, SpringBoot Embedded Tomcat Server, STS-Eclipse IDE
Tools to be used
° Use any IDE to develop the Spring and Hibernate project. It may be STS/Eclipse/Netbeans. Here, we are using STS (Spring Tool Suite).
° Mysql for the database.
° Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.
° Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.
Spring MVC
Spring MVC is the primary web framework built on the Servlet API. It is build on the popular MVC design pattern. MVC (Model-View-Controller) is a software architecture pattern, which separates application into three areas: model, view, and controller. The model represents a Java object carrying data. The view represents the visualization of the data that the model contains. The controller controls the data flow into model object and updates the view when the data changes. It separates the view and model.
Spring Boot Architecture
Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. It is developed on top of the core Spring Framework.
Introduction mysql to database
MySQL is a database management system that allows you to manage relational databases. It is open source software backed by Oracle. It means you can use MySQL without paying a dime. Also, if you want, you can change its source code to suit your needs. MySQL can run on various platforms UNIX, Linux, Windows, etc. You can install it on a server or even in a desktop. Besides, MySQL is reliable, scalable, and fast.
Introduction to the POM
POM A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/main/java; and so on. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0>/modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/>
</parent>
<groupId>org.enterprise</groupId>
<artifactId>enterprise</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>enterprise</name>
<description>Demo project for Spring Boot</description>
<properties>
<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-web</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application.properties file under the classpath.
The application.properties file is located in the src/main/resources directory. The code for sample application.properties
We need to create database name it bank
src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/enterprise?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.activemq.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
server.port=8080
spring.jpa.database=MYSQL
Class Diagram
Modals / Entities
An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.
We need to create these entities
-> Application
-> Enterprise
-> User
-> Criticality
-> Language
Here, we are creating an Entity
Application.java This object content id, name, description and two Enums Criticality and Language and relational @ManyToOne with Enterprise and @OneToOne with User, we need also implements Visitable this interface we will create in the backage visitor
src/main/java/com/enterprise/model/Application.java):
package com.enterprise.modal;
import javax.persistence.*;
import com.enterprise.visitor.Visitable;
import com.enterprise.visitor.Visitor;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Application implements Visitable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(columnDefinition="VARCHAR(40)")
private String name;
@Column(columnDefinition = "TEXT")
private String description;
@Enumerated(EnumType.STRING)
private Language language;
@Enumerated(EnumType.STRING)
private Criticality criticality;
@JsonBackReference(value = "user")
@OneToOne(cascade = CascadeType.ALL)
private User user;
@JsonBackReference(value = "enterprise")
@ManyToOne
private Enterprise enterprise;
public Application() {
super();
}
public Application(String name, String description, Language language, Criticality criticality, User user,
Enterprise enterprise) {
super();
this.name = name;
this.description = description;
this.language = language;
this.criticality = criticality;
this.user = user;
this.enterprise = enterprise;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public Criticality getCriticality() {
return criticality;
}
public void setCriticality(Criticality criticality) {
this.criticality = criticality;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Enterprise getEnterprise() {
return enterprise;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
Here, we are creating an Entity
Enterprise.java This object content id, name
src/main/java/com/enterprise/model/Enterprise.java):
package com.enterprise.modal;
import javax.persistence.*;
import com.enterprise.visitor.Visitable;
import com.enterprise.visitor.Visitor;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Enterprise implements Visitable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(columnDefinition="VARCHAR(40)")
private String name;
@Column(columnDefinition = "TEXT")
private String description;
@OneToMany(mappedBy="enterprise", cascade = CascadeType.ALL)
private List<Application> applications;
public Enterprise() {
super();
}
public Enterprise(String name, String description, List<Application> applications) {
super();
this.name = name;
this.description = description;
this.applications = applications;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Application> getApplications() {
return applications;
}
public void setApplications(List<Application> applications) {
this.applications = applications;
}
public void addApplication(Application app) {
if (getApplications() == null) {
this.applications = new ArrayList<Application>();
}
getApplications().add(app);
app.setEnterprise(this);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
if (getApplications() != null) {
getApplications().forEach(application -> {
application.accept(visitor);
});
}
}
}
Here, we are creating an Entity
User.java This object content id, name, and relational @ManyToOne with Sport and Gym
src/main/java/com/enterprise/model/User.java):
package com.enterprise.modal;
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(columnDefinition="VARCHAR(40)")
private String name;
public User() {
super();
}
public User(String name) {
super();
this.name = name;
}
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;
}
Enum
Here, we are creating an enum Criticality
src/main/java/com/enterprise/model/Criticality.java):
import com.enterprise.modal;
public enum Criticality {
LOW, MEDIUM, HIGH
}
Here, we are creating an enum Language
src/main/java/com/enterprise/model/Language.java):
package com.enterprise.modal;
public enum Language {
JAVA, JAVASCRIPT, PHP
}
Visitor Design Pattern
The purpose of a Visitor pattern is to define a new operation without introducing the modifications to an existing object structure. Imagine that we have a composite object which consists of components. The object's structure is fixed – we either can't change it, or we don't plan to add new types of elements to the structure. Now, how could we add new functionality to our code without modification of existing classes? The Visitor design pattern might be an answer. Simply put
We'll have to do is to add a function which accepts the visitor class to each element of the structure.
That way our components will allow the visitor implementation to “visit” them and perform any required action on that element. In other words, we'll extract the algorithm which will be applied to the object structure from the classes. Consequently,
We'll make good use of the Open/Closed principle
As we won't modify the code, but we'll still be able to extend the functionality by providing a new Visitor implementation.
We need to create these interfaces
-> Visitable
-> Visitor
Here, we are creating an interface Visitable
src/main/java/com/enterprise/visitor/Visitable.java):
package com.enterprise.visitor;
public interface Visitable {
void accept(Visitor visitor);
}
Here, we are creating an interface
src/main/java/com/enterprise/model/Visitor.java):
package com.enterprise.visitor;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.User;
public interface Visitor {
int visit(Enterprise enterprise);
int visit(Application application);
int visit(User user);
}
Calculate
We will calculate the criticalities and the languages in these entities.
We need to create these interfaces
-> CalculateHigh
-> CalculateJava
-> CalculateJavascript
-> CalculateLow
-> CalculateMedium
-> CalculatePhp
Here, we are creating an entity CalculateHigh
CalculateHigh.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculateHigh.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculateHigh implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getCriticality() == Criticality.HIGH) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Here, we are creating an entity CalculateJava
CalculateJava.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculateJava.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculateJava implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getLanguage() == Language.JAVA) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Here, we are creating an entity CalculateJavascript
CalculateJavascript.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculateJavascript.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculateJavascript implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getLanguage() == Language.JAVASCRIPT) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Here, we are creating an entity CalculateLow
CalculateLow.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculateLow.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculateLow implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getCriticality() == Criticality.LOW) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Here, we are creating an entity CalculateMedium
CalculateMedium.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculateMedium.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculateMedium implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getCriticality() == Criticality.MEDIUM) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Here, we are creating an entity CalculatePhp
CalculatePhp.java We are going implements Visitor to @Override the visit method
src/main/java/com/enterprise/calculator/CalculatePhp.java):
package com.enterprise.calculator;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.Language;
import com.enterprise.modal.User;
import com.enterprise.visitor.Visitor;
public class CalculatePhp implements Visitor {
private int value = 0;
@Override
public int visit(Enterprise enterprise) {
return 0;
}
@Override
public int visit(Application application) {
if(application.getLanguage() == Language.PHP) {
value++;
}
return value;
}
@Override
public int visit(User user) {
return 0;
}
public int getValue() {
return value;
}
}
Spring Data JPA Projections
When using Spring Data JPA to implement the persistence layer, the repository typically returns one or more instances of the root class. However, more often than not, we don't need all the properties of the returned objects.
In such cases, it may be desirable to retrieve data as objects of customized types. These types reflect partial views of the root class, containing only properties we care about. This is where projections come in handy.
We need to create these interface dao
-> ApplicationDao
-> EnterpriseDao
-> UserDao
Here, we are creating an interface ApplicationDao
src/main/java/com/enterprise/dao/ApplicationDao.java):
package com.enterprise.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.enterprise.modal.Application;
public interface ApplicationDao extends JpaRepository<Application, Long> {
}
Here, we are creating an interface EnterpriseDao
src/main/java/com/enterprise/dao/EnterpriseDao.java):
package com.enterprise.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.enterprise.modal.Enterprise;
public interface EnterpriseDao extends JpaRepository<Enterprise, Long> {
}
Here, we are creating an interface UserDao
src/main/java/com/enterprise/dao/UserDao.java):
package com.enterprise.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.enterprise.modal.User;
public interface UserDao extends JpaRepository<User, Long> {
}
The services
Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here
We will create one interface in service package:
-> ApplicationService
-> EnterpriseService
-> UserService
Here, we are creating an interface ApplicationService
src/main/java/com/enterprise/service/ApplicationService.java):
package com.enterprise.service;
import java.util.List;
import com.enterprise.modal.Application;
public interface ApplicationService {
Application createApplicationForUser(Application application, long id);
Application createApplicationForEnterprise(long idApplication, long id);
List<Application> findApplications();
List<Application> findApplicationsForEnterprise(long id);
Application findApplication(long id);
void deleteApplication(long id);
}
Here, we are creating an interface EnterpriseService
src/main/java/com/enterprise/service/EnterpriseService.java):
package com.enterprise.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.enterprise.modal.Enterprise;
public interface EnterpriseService {
Enterprise createEnterprise(Enterprise enterprise);
List<Enterprise> findEnterprises();
Enterprise findEnterprise(long id);
void deleteEnterprise(long id);
int calculateJava(Enterprise enterprise);
int calculateLow(Enterprise enterprise);
int calculateMedium(Enterprise enterprise);
int calculatePhp(Enterprise enterprise);
int calculateHigh(Enterprise enterprise);
int calculateJavascript(Enterprise enterprise);
}
Here, we are creating an interface UserService
src/main/java/com/enterprise/service/UserService.java):
package com.enterprise.service;
import java.util.List;
import com.enterprise.modal.User;
public interface UserService {
User createUser(User user);
List<User> findUsers();
}
The managers classes implementation
An impl class is usually a class that implements the behaviour described by one of these interfaces. While the internal implementation class, With transactions configured, we can now annotation a bean with @Transactional and @Service either at the class or method level. Then conversion Entity to DTO. This is stands for Data Transfer Object and is a simple Plain Old Java Object which contains class properties and getters and settings methods for accessing those properties.
We will create one interface in impl package:
-> ApplicationServiceImpl
-> EnterpriseServiceImpl
-> UserServiceImpl
Here, we are creating an class ApplicationServiceImpl
src/main/java/com/enterprise/impl/ApplicationServiceImpl.java):
package com.enterprise.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.enterprise.dao.ApplicationDao;
import com.enterprise.dao.EnterpriseDao;
import com.enterprise.dao.UserDao;
import com.enterprise.modal.Application;
import com.enterprise.modal.Enterprise;
import com.enterprise.modal.User;
import com.enterprise.service.ApplicationService;
@Transactional
@Component
public class ApplicationServiceImpl implements ApplicationService{
@Autowired
private ApplicationDao applicationDao;
@Autowired
private UserDao userDao;
@Autowired
private EnterpriseDao enterpriseDao;
@Override
public Application createApplicationForUser(Application application, long id) {
User user = userDao.findById(id).orElse(null);
application.setUser(user);
return applicationDao.save(application);
}
@Override
public List<Application> findApplications() {
return applicationDao.findAll();
}
@Override
public Application findApplication(long id) {
return applicationDao.findById(id).orElse(null);
}
@Override
public void deleteApplication(long id) {
Application application = applicationDao.findById(id).orElse(null);
application.setUser(null);
applicationDao.delete(application);
}
@Override
public Application createApplicationForEnterprise(long idApplication, long id) {
Enterprise enterprise = enterpriseDao.findById(id).orElse(null);
Application application = applicationDao.findById(idApplication).orElse(null);
enterprise.addApplication(application);
return applicationDao.save(application);
}
@Override
public List<Application> findApplicationsForEnterprise(long id) {
Enterprise enterprise = enterpriseDao.findById(id).orElse(null);
return enterprise.getApplications();
}
}
Here, we are creating an interface EnterpriseServiceImpl
src/main/java/com/enterprise/impl/EnterpriseServiceImpl.java):
package com.enterprise.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.enterprise.calculator.CalculateHigh;
import com.enterprise.calculator.CalculateMedium;
import com.enterprise.calculator.CalculateJava;
import com.enterprise.calculator.CalculateJavascript;
import com.enterprise.calculator.CalculateLow;
import com.enterprise.calculator.CalculatePhp;
import com.enterprise.dao.EnterpriseDao;
import com.enterprise.modal.Enterprise;
import com.enterprise.service.EnterpriseService;
@Transactional
@Component
public class EnterpriseServiceImpl implements EnterpriseService {
@Autowired
private EnterpriseDao enterpriseDao;
@Override
public Enterprise createEnterprise(Enterprise enterprise) {
return enterpriseDao.save(enterprise);
}
@Override
public List<Enterprise> findEnterprises() {
return enterpriseDao.findAll();
}
@Override
public Enterprise findEnterprise(long id) {
return enterpriseDao.findById(id).orElse(null);
}
@Override
public void deleteEnterprise(long id) {
enterpriseDao.deleteById(id);
}
@Override
public int calculateJava(Enterprise enterprise) {
CalculateJava calculateJava = new CalculateJava();
enterprise.accept(calculateJava);
return calculateJava.getValue();
}
@Override
public int calculateLow(Enterprise enterprise) {
CalculateLow calculateLow = new CalculateLow();
enterprise.accept(calculateLow);
return calculateLow.getValue();
}
@Override
public int calculateMedium(Enterprise enterprise) {
CalculateMedium calculateMedium = new CalculateMedium();
enterprise.accept(calculateMedium);
return calculateMedium.getValue();
}
@Override
public int calculatePhp(Enterprise enterprise) {
CalculatePhp calculatePhpApps = new CalculatePhp();
enterprise.accept(calculatePhpApps);
return calculatePhpApps.getValue();
}
@Override
public int calculateJavascript(Enterprise enterprise) {
CalculateJavascript calculateJavascript = new CalculateJavascript();
enterprise.accept(calculateJavascript);
return calculateJavascript.getValue();
}
@Override
public int calculateHigh(Enterprise enterprise) {
CalculateHigh calculateHigh = new CalculateHigh();
enterprise.accept(calculateHigh);
return calculateHigh.getValue();
}
}
Here, we are creating an Entity UserServiceImpl
src/main/java/com/enterprise/impl/UserServiceImpl.java):
package com.enterprise.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.enterprise.dao.UserDao;
import com.enterprise.modal.User;
import com.enterprise.service.UserService;
@Transactional
@Component
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public User createUser(User user) {
return userDao.save(user);
}
@Override
public List<User> findUsers() {
return userDao.findAll();
}
}
@RestController API
@RestController is a convenience annotation for creating Restful controllers. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML. It does not work with the view technology, so the methods cannot return ModelAndView. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.
We will create one interface in controller package:
-> ApplicationController
-> EnterpriseController
-> UserController
Here, we are creating an Entity ApplicationController
src/main/java/com/enterprise/controller/ApplicationController.java):
package com.enterprise.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.enterprise.modal.Application;
import com.enterprise.service.ApplicationService;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
public class ApplicationController {
@Autowired
private ApplicationService applicationService;
@PostMapping("/createApplication/{id}")
Application createApplication(@RequestBody Application application, @PathVariable long id) {
return applicationService.createApplicationForUser(application, id);
}
@PostMapping("/createApplicationForEnterprise/{idApplication}/{id}")
Application createApplicationForEnterprise(@PathVariable long idApplication, @PathVariable long id) {
return applicationService.createApplicationForEnterprise(idApplication, id);
}
@GetMapping("/findApplications")
List<Application> findApplications() {
return applicationService.findApplications();
}
@GetMapping("/findApplicationsForEnterprise/{id}")
List<Application> findApplicationsForEnterprise(@PathVariable long id) {
return applicationService.findApplicationsForEnterprise(id);
}
@GetMapping("/findApplication/{id}")
Application findApplication(@PathVariable long id) {
return applicationService.findApplication(id);
}
@DeleteMapping("/deleteApplication/{id}")
void deleteApplication(@PathVariable long id) {
applicationService.deleteApplication(id);
}
}
Here, we are creating an Entity EnterpriseController
src/main/java/com/enterprise/conntroller/EnterpriseController.java):
package com.enterprise.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.enterprise.dao.EnterpriseDao;
import com.enterprise.modal.Enterprise;
import com.enterprise.service.EnterpriseService;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
public class EnterpriseController {
@Autowired
private EnterpriseService enterpriseService;
@Autowired
private EnterpriseDao enterpriseDao;
@PostMapping("/createEnterprise")
Enterprise createEnterprise(@RequestBody Enterprise enterprise) {
return enterpriseService.createEnterprise(enterprise);
}
@GetMapping("/findEnterprises")
List<Enterprise> findEnterprises() {
return enterpriseService.findEnterprises();
}
@GetMapping("/findEnterprise/{id}")
Enterprise findEnterprise(@PathVariable long id) {
return enterpriseService.findEnterprise(id);
}
@DeleteMapping("/deleteEnterprise/{id}")
void deleteEnterprise(@PathVariable long id) {
enterpriseService.deleteEnterprise(id);
}
@GetMapping("/calculateJava/{id}")
int calculateJavaApps(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculateJava(enterprise);
}
@GetMapping("/calculateLow/{id}")
int calculateLowApps(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculateLow(enterprise);
}
@GetMapping("/calculateMedium/{id}")
int calculateLowAndJava(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculateMedium(enterprise);
}
@GetMapping("/calculatePhp/{id}")
int calculatePhpApps(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculatePhp(enterprise);
}
@GetMapping("/calculateHigh/{id}")
int calculateHighApps(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculateHigh(enterprise);
}
@GetMapping("/calculateJavascript/{id}")
int calculateHigtAndPhp(@PathVariable long id) {
Enterprise enterprise = enterpriseDao.findById(id).get();
return enterpriseService.calculateJavascript(enterprise);
}
}
Here, we are creating an Entity UserController
src/main/java/com/enterprise/controller/UserController.java):
package com.enterprise.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.enterprise.modal.User;
import com.enterprise.service.UserService;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/createUser")
User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping("/findUsers")
List<User> findUsers() {
return userService.findUsers();
}
}
EnterpriseApplication
@BookStoreApplication and its use in a simple Spring Boot application. We use the @SpringBootApplication annotation in our Application or Main class to enable a host of features, e.g. Java-based Spring configuration, component scanning, and in particular for enabling Spring
src/main/java/com/note/EnterpriseApplication.java):
package com.enterprise;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EnterpriseApplication {
public static void main(String[] args) {
SpringApplication.run(EnterpriseApplication.class, args);
System.out.println("App started....");
}
}
Conclusion
Now we have an overview of Spring Boot example when building a @RestController API.
We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data JPA, and The Visitor pattern is great to separate the algorithm from the classes on which it operates. Besides that, it makes adding new operation more easily, just by providing a new implementation of the Visitor. as well, we are gooing to continue with Ionic project structure for building a front-end app to make HTTP requests and consume responses.