This tutorial for beginners who are interested to learn basics of Spring Boot and Spring MVC working together. At the end of this tutorial, you could run a simple SPring MVC application using Spring Boot.
Spring Boot is a Spring IO Project aimed at reducing the Spring application startup configurations and wiring. Developer has to focus on only writing the application while Spring Boot will simplify the deployment process by packaging and deploying your application without any explicit configurations. It just works out of the box!!. Here I will explain how to run a simple Spring MVC application using Spring Boot that also performs CRUD operations. Before start this example, please create web project in eclipse.
- Also Read : Introduction to Spring Boot
I have written a example that does the following tasks:
- Created a web page
- User can add employee to database
- User can view the list of employees added to database in the browser (JSON result)
The above tasks are performed using Spring MVC, Hibernate and Spring Boot.
Create Domain Class
First create a domain class Employee to store the details about an Employee. It is simple POJO class.
@Entity public class Employee { @Id @NotNull @Size(max = 64) @Column(name = "id", nullable = false, updatable = false) private String id; @NotNull @Size(max = 64) @Column(name = "name", nullable = false) private String name; @NotNull @Size(max = 64) @Column(name = "city", nullable = false) private String city; Employee() { } public Employee(final String id, final String name,final String city) { this.id = id; this.name = name; this.city = city; } public String getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return Objects.toStringHelper(this) .add("id", id) .add("name", name) .add(city, city) .toString(); } }
Create Spring Data JPA Repository
Spring Data JPA is very easy way to persist data in to back end. If you look at the below code, that is all you are going to write for persisting your Employee class. Spring Data internally implement the necessary files and do the CRUD operations on behalf of you. You just need to provide the interface as below. If you are interested in learning Spring Data, please read our Spring Data JPA tutorial.
public interface EmployeeRepository extends JpaRepository<Employee, String> { }
Create Service Implementation
@Service @Validated public class EmployeeServiceImpl implements EmployeeService { private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeServiceImpl.class); private final EmployeeRepository repository; @Inject public EmployeeServiceImpl(final EmployeeRepository repository) { this.repository = repository; } @Transactional public Employee save(@NotNull @Valid final Employee employee) { LOGGER.debug("Creating {}", employee); return repository.save(employee); } @Transactional(readOnly = true) public List<Employee> getList() { LOGGER.debug("Retrieving the list of all users"); return repository.findAll(); } }
Create Spring MVC Controller
Nothing new for Spring developers, we are just creating a simple Spring MVC controller for adding and listing the employee details.
@RestController public class EmployeeController { private final EmployeeService employeeService; @Inject public EmployeeController(final EmployeeService employeeService) { this.employeeService = employeeService; } @RequestMapping(value = "/employee", method = RequestMethod.GET) public List<Employee> listEmployees() { List<Employee> employees = employeeService.getList(); return employees; } @RequestMapping(value="/add",method = RequestMethod.GET) public void addEmployee(@RequestParam(value = "employeeName", required = false) String employeeName, @RequestParam(value = "employeeId", required = false) String employeeId, @RequestParam(value = "employeeCity", required = false) String employeeCity){ Employee employee = new Employee(employeeId,employeeName,employeeCity); employeeService.save(employee); } }
Create JSP File
<!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> </head> <body> <form action="/add"> <input type="input" name="employeeName"> <input type="input" name="employeeId"> <input type="input" name="employeeCity"> <input type="submit"> </form> </body> </html>
Spring Boot Application
Finally, we have to write the Spring Boot application to run our example. This is the main application that will be invoked by Spring Boot when you try to execute the application.
- Also Read : REStful API using Spring Boot
@EnableAutoConfiguration
This annotation tries to find the beans that are necessary to run the application by looking at the classpath. or example, If you have tomcat-embedded.jar
on your classpath you are likely to want a TomcatEmbeddedServletContainerFactory
. The package of the class that is annotated with @EnableAutoConfiguration
has special significance and is often used as a ‘default’. For example, it will be used when scanning for @Entity
classes. It is generally recommended that you place @EnableAutoConfiguration
in a root package so that all sub-packages and classes can be searched.
SpringApplication.run()
SpringApplication class is used for bootstrap and launch spring application. The bootstrap of an spring application consists of creating appropriate application context, loading beans, trigger any command line beans, etc.
SpringBootServletInitializer
This is required to run the web application. This will enable the servlet container and bind your application to the servlet container.
@Configuration @EnableAutoConfiguration @ComponentScan public class Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } @Override protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) { return application.sources(Application.class); } }
Maven Configurations
This is the important part running the Spring Boot application. Spring Boot has to identify the dependencies for running an application by looking at the build files. It can support wide variety of build tools, but spring boot’s official documentation emphasize more on Maven and Gradle configurations. So, it is wise to choose any one for the easy implementation.
spring-boot-starter-*
Starter POM’s are pre-defined POM’s descriptors that are available as in-built. You need not search for the dependencies and configure it. For example, if you are looking for Spring and JPA for data access, you have to just include spring-boot-starter-data-jpa to your POM file.
spring-boot-maven-plugin
This plug-in allows you to package your application into an executable JAR or WAR file. This is supported from Maven 3.2 on wards. In our example, when you have run the project using the “mvn install” command, maven would build the project and create the executable JAR file under the target folder. Please look at the below folder structure.
spring-boot-starter-parent
If you want to inherit the properties from the spring-boot-starter-parent, then simply set the parent. If you use the parent, then version numbers can be omitted for other starters used in the POM. If you have your own parent for your projects, then you can use them instead of the default parent provided by spring boot. It looks like this:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.0.1.RELEASE</version> </parent>
The final package structure for the project looks like this. Here I have create Application.java under a package. But, it is good practice to keep this file in the root package.
The entire source code can be downloaded at the bottom of this tutorial.
<dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Hibernate validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <!-- HSQLDB --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>runtime</scope> </dependency> <!-- Guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <!-- Java EE --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> </dependencies> <build> <plugins> <!-- Spring Boot Maven --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
Run Spring Boot From Executable JAR File
Once you have built the application, run this command to execute your application.
java -jar target/mymodule-0.0.1-SNAPSHOT.jar
Once run the above command from your command application, spring boot application will run the application in the path http://localhost:8080/. You can access the index page of the application at http://localhost:8080/index.jsp:
You can add many number of rows. When you access the URL http://localhost:8080/employee, you would get an out something like this in the browser window:
[{"id":"Krishna","name":"001","city":"Bangalore"},{"id":"Manisha Patil","name":"005","city":"Pune"},{"id":"Sanulla","name":"001","city":"Bangalore"},{"id":"Shunmuga Raja","name":"001","city":"Bangalore"}]
Source Code Download
Summary
We have discussed in this article about how to create a maven project and creating the different components required for the Employee manager Spring MVC application. Later we have explored the Spring Boot configuration details and Maven POM file content required for the Spring Boot application. Finally we have talked about running the executable JAR file that is packaged using the Maven build. At the end of this tutorial, you will be able to get an idea about how spring boot and spring mvc working together.
If you have any questions about the spring boot applications, please write it in the comments section.