Home » Spring Boot Tutorial » Spring Boot – Code Structuring

Spring Boot – Code Structuring


Reading Time - 12 mins

The following tutorial gives you an overview of the Spring boot Code structuring and some of the main classes and annotations used in the code.

Code Layout

Spring boot does not force you to use any particular code structure. We can always follow certain best coding practices suggested by the Spring Team.

For example, Spring does not recommend using the default package. Also, it is always better to follow Java naming conventions and follow a reversed domain name (For instance, com.example.demo).

A typical code layout will be as follows:

Code Layout of Spring Boot Application

Main Application Class

  • Spring Boot recommends placing the main application class in the root package. All the other packages below this root package are automatically scanned and auto-configured within Spring Context.
  • In the above code layout, DemoApplication.java is the main class that contains the main() method.
  • Refer the following code snippet of DemoApplication.java :
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

}

Notice the annotation @SpringBootApplication placed on the main class.

  • This is a flagship annotation of Spring Boot that initializes the spring context and auto-scans the components (equivalent to @ComponentScan annotation) below the root package and auto-configures the Spring Boot Application. (equivalent to @EnableAutoConfiguration annotation).
  • This @SpringBootApplication is equivalent to declaring the following 3 annotations:
    1. @Configuration – Defined on top of Beans. Acts as a source of bean definitions.
    2. @EnableAutoConfiguration – This annotation gives an idea to auto-configure the Spring Boot application based on the libraries present on the CLASSPATH. For example, if JPA libraries are available on the CLASSPATH, then it auto-configures the application as a Spring JPA Application.
    3. @ComponentScan – Gives an idea to Spring Boot where to search for components, including @Configuration classes.
READ  Spring Boot - Working with Embedded Databases

The practical usage of the above annotations will be explained in the later tutorials.

XML based Configuration

  • Spring Boot favors Java Based configurations and does not recommend using XML based configuration.
  • If there is an absolute need to use XML based configuration, you can start with a main @Configuration class, and then import the XML bean configurations using @ImportResource annotation.
  • Refer the following code snippet for the usage of @ImportResource annotation in the main application class:
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("com/example/resources/appConfig.xml")
public class SampleApp {
  
  public static void main(String[] args) {
    SpringApplication.run(SampleApp.class, args);
  }
}
  • Refer the following XML configurations to register a bean named “CustomerBean” with the Spring Context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
 <bean id="beanB" class="com.example.demo.bean.CustomerBean" />
 
 </beans>
  • Now, finally refer to the CustomerBean defined in the package “com.example.demo.bean” is shown below:
package com.example.demo.bean;

public class CustomerBean {
  
  public CustomerBean() {

    System.out.println("***********In CustomerBean : ***********");
  }

}
  • Now, Run the SampleApp.java as shown in the following screenshot:
  • For your reference, Right Click on SampleApp.java and select “Run As –> Java Application”:
  • Notice that the Customer Bean is initialized within the Spring Context in the following output :
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-03-05 22:48:54.516  INFO 10194 --- [           main] com.example.demo.SampleApp               : Starting SampleApp on m-c02qg7nkg8wn with PID 10194 (/Users/vn0mrcb/Documents/workspace-spring-tool-suite-4-4.1.2.RELEASE1/demo/target/classes started by vn0mrcb in /Users/vn0mrcb/Documents/workspace-spring-tool-suite-4-4.1.2.RELEASE1/demo)
2019-03-05 22:48:54.518  INFO 10194 --- [           main] com.example.demo.SampleApp               : No active profile set, falling back to default profiles: default
2019-03-05 22:48:56.000  INFO 10194 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-03-05 22:48:56.031  INFO 10194 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-03-05 22:48:56.032  INFO 10194 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-03-05 22:48:56.041  INFO 10194 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/vn0mrcb/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2019-03-05 22:48:56.129  INFO 10194 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-03-05 22:48:56.130  INFO 10194 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1564 ms
**********In CustomerBean :********** 
2019-03-05 22:48:56.643  INFO 10194 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-03-05 22:48:56.907  INFO 10194 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-03-05 22:48:56.973  INFO 10194 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-03-05 22:48:56.977  INFO 10194 --- [           main] com.example.demo.SampleApp               : Started SampleApp in 2.813 seconds (JVM running for 3.19)
2019-03-05 22:49:00.174  INFO 10194 --- [)-192.168.0.101] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-03-05 22:49:00.174  INFO 10194 --- [)-192.168.0.101] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-03-05 22:49:00.183  INFO 10194 --- [)-192.168.0.101] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms

Welcome Controller

  • As part of the code layout, in addition to the main class, notice the Controller class named HelloWebController.java present in a sub-package within the root package.
  • As this is a web application, this Controller is responsible for handling web requests. (For instance, GET and POST Requests).
  • Refer the following code present in HelloWebController.java:
package com.example.demo.controller;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloWebController {
  
   @RequestMapping("/")
      public String index() {
          return "Hello World!!";
      }
  }
  • Notice the following annotations present in the Controller:
    1. @RestController – Indicates that an annotated class is a “Controller” (e.g. a web controller).
    2. @RequestMapping – Ensures mapping to the index() method in the Controller class for requests starting with “/hello”.
  • Also, note that since we have not specified the mode of HTTP Requests that the RequestMapping supports, it handles all the HTTP Requests (i.e., GET, POST etc…).
READ  Spring Boot - Internationalization

Application Properties

  • Spring Boot reduces the complex XML configurations present in Spring Framework and changed it into a simple properties file.(application.properties)
  • This file is present under “src/main/resources” package. This is auto-created when you create a simple Hello World web application as per the previous tutorial on Creating your First Spring Boot Application.
  • By default, Spring Boot auto-detects the default properties present in this file and the developer has the flexibility to override any property if needed.

Conclusion

  • To conclude, In this tutorial, we have learned the Code structuring in a Spring Boot application. Also, we got an overview of all the major annotations in the Spring Boot context.
  • If you have any further doubts, please refer to the links present in the References section.
  • In the next tutorial, we will be dealing with Developer Tools that help in debugging purposes and various advanced Spring Boot features.

References

  • As a next step, refer the following links:

Structuring your code

Common Application Properties

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions