Structure you Spring boot Application

In this post we will structure our previously build application. We will create model for entity, services for business logic, repository for persistence and controller for endpoints. Why structuring your application is so important? Because when enterprise applications grows it becomes a pain to maintain the application.

So let’s make it happen

  1. Let’s get started. Jump to Spring Initialize (http://start.spring.io/) to generate our project.
  2.  Add few dependencies which will be required to build our application. Dependencies includes Web for REST, MySQL for JDBC Driver and JPA for persistence. And generate project.
  3. Once you have the downloaded project in your system, open your favorite IDE and import the project. And resolve all dependencies we included. Once dependencies are resolved we are good to code our requirement.First we need a model which will act as an Entity for us and help use saving data in our Database.
    package com.javatab.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import java.io.Serializable;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @Entity //Tells it's the entity which will be stored in DB
    public class User implements Serializable{
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id; // Column: ID, primary generated by JPA
        private String name; // Column: Name
    
        public User() {
        }
    
        public User(String name) {
            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;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
  4. We will create a repository by extending JpaRepository which is provide by spring data module. It will give some very simple yet powerful sql query implementation out of the box. You needn’t to write. Please refer documentation here
    package com.javatab.repository;
    
    import com.javatab.model.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    }
  5. Now we have to create a Service which will hold all our business logic. To hide our business logic implementation we will service interface.
    package com.javatab.service;
    
    import com.javatab.model.User;
    
    import java.util.List;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    public interface UserService {
    
        User save(User user);
        List<User> getAllUsers();
    }
  6. Let’s implement our abstract method in UserService interface. Our implementation class will hold all the logic to save data to the database and send the saved data to our controller which will give it back to the client. A client can be a Mobile or Web. So to implement the business we need instance of our repository. The class will be spring annotation called @Transactional and @Service.
    package com.javatab.service;
    
    import com.javatab.model.User;
    import com.javatab.repository.UserRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @Service
    @Transactional
    public class UserServiceImpl implements UserService {
    
        private UserRepository userRepository;
    
        @Autowired
        public UserServiceImpl(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        @Override
        public User save(User user) {
            return userRepository.save(user);
        }
    
        @Override
        public List<User> getAllUsers() {
            return userRepository.findAll();
        }
    }
  7. Now it’s time to expose our service which holds our business logic. It can be achieved by creating a controller class using annotation called @RestController. We will inject our service layer in controller which will provide all service implementation in our controller. To invoke specific service which within service layer we need to create respective methods for them. The method can be annotated with @RequestMapping which has some self explanatory metadata.
    package com.javatab.web.api;
    
    import com.javatab.model.User;
    import com.javatab.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * Created by nasruddin on 18/6/16.
     */
    @RestController
    public class UserController {
    
        private UserService userService;
    
        @Autowired
        public UserController(UserService userService) {
            this.userService = userService;
        }
    
        @RequestMapping(
                value = "/api/user/create",
                method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<User> createUser(@RequestBody User user) {
    
            User savedUser = userService.save(user);
            return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
        }
    
        @RequestMapping(
                value = "/api/user",
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<List<User>> getUsers() {
    
            List<User> users = userService.getAllUsers();
    
            return new ResponseEntity<>(users, HttpStatus.OK);
    
        }
    }
  8. We are all done. Lets run our application. Open terminal, go to project directory and run ./gradlew clean bootRunSelection_027
  9. Now the application is running. It’s good time to test them. Open any rest client. In my case I’m using chrome plugin called Postman. Let’s hit our APIs. First create some users. You can hit http://localhost:8080/api/user/create which is a POST and pass raw data as { “name”: “Name 1” } Selection_028.pngNow to fetch the saved user we can hit http://localhost:8080/api/user which is a GET. It will return list of all saved user.Selection_029.png

If you are using Intellij you run the application in Debug mode and hit the APIs. And you can figure how Spring boot creates database on the fly. Creates SQL queries for us.Selection_030.png

Source Code on GitHub

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s