Monday, 22 March 2021

How to quick start with Spring boot ?

EXAMPLE : Create a simple API

PRE-REQUISITES TO QUICK START WITH SPRING BOOT :

 - JDK
 - IDE
   STS (Spring Tool Suite) - wrapper over eclipse providing all the Spring boot support.
    OR
    Eclipse with Spring boot plugin
 - Maven (Dependency management tool + Build tool) : declares all the dependencies (in pom.xml) instead of downloading & putting Jars in classpath 


1. Open IDE > Create new project > Maven project

2. Provide project config :
    Check Create simple project
    Provide group id = com.shaan , artifact id = userapi , packaging = Jar
    Click Finish

    creates : 
    - project skeleton (src/main/java, src/main/resource, src/test/java, src/test/resource)
    - pom.xml with info provided in project config
    - JRE libs

3. Set Java version :
    <property>
       <java.version>1.8</
java.version>
    </property>

4. Add spring dependency as parent (inherits all spring boot dependencies + config in the application) :
    <parent>
       <groupId>org.springFramework.boot<groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.4.2.RELEASE</version>
     </parent>

5. Add Web application dependency (As we need to create a REST API)

    <depedencies>
       <groupId>org.springFramework.boot<groupId>
       <artifactId>spring-boot-starter-web</artifactId>
     </
depedencies>

After saving pom.xml, it will add all the required Jars under : 
   - Maven dependencies

6. Update project config with pom.xml  (There may be errors in markers tab of IDE)
  - Right click on project name > Maven > Update project

7. Create a main Java class : MainApi
   
@SpringBootApplication
  public clas MainApi {
       p.s.v.p.(String[] args) {
         
// static method taking class having main()                          SpringApplication.run(UserApi.clas, args);
       }
  }

If you run MainApi class, with the help of Spring boot it will :
  - Setup config
  - Start Spring application context 
  - Check class paths (registers annotations)
  - Run container (embedded tomcat server)

8. Create REST controller (API which can handle HTTP requests)
@RestController
public class UserController {
   
// Method mapping with URL
    @RequestMapping("/hello")
    public String show() {
        return "Hello";
    }
}

9. Run MainApi class
It will enable registration of all the annotations and able to expose the API using controller. Once the sever is started you can test it.

10. Test your API 
 - Open browser and call API through declared URL : localhost:8080/hello


No comments:

Post a Comment

Note: only a member of this blog may post a comment.