DEV Community

KamalaKannan
KamalaKannan

Posted on

SpringBoot Core Concepts and Annotations

Why Spring?
It is a Java Framework which simplifies complex backend development, reduces boilerplate code, and promotes loose coupling via Dependency Injection
Important Keywords
*Dependency Injection(managing object lifecycles and dependencies, leading to loosely coupled, easier-to-maintain code.)
*IoC(Inversion of Control) =>implies that the control of creating, managing and deleting of objects given to spring (Inversing the control from dev to framework). It is a concept name which is used to achieve Dependency Injection.
*IoC Container => It is small memory block created inside JVM by spring to manage all the beans. Every beans created inside this container instead of created in heap memory and this container is managed by Spring itself.

Why SpringBoot over Spring?
Spring Boot is an extension of the Spring Framework designed to simplify development by removing the manual configuration and boilerplate code required in traditional Spring projects.
Adavantages of using SpringBoot over Spring.
*Auto-Configuration => As a developer we dont need work around in configuration which consumes more time in Spring.
*Embedded Server => Unlike Spring, SpringBoot has its own embedded server which allows you to package your application as a standalone executable JAR file that "just runs," eliminating the need to manually set up and deploy to an external web server.
*Starter Dependencies => Instead of managing dozens of individual libraries, Spring Boot provides Starter POMs (e.g., spring-boot-starter-web) that bundle all necessary dependencies for a specific task into a single, managed package.

Types of Dependency Injection:
1.Field Injection => Dependencies are injected directly into private fields using @Autowired
Example:
public class MyService {
@Autowired
private MyRepository repository; // Injected directly
}
2.Setter Injection => Use this for optional dependencies or values that can change after creation
Example:
public class MyService {
private MyRepository repository;
@Autowired
public void setRepository(MyRepository repository) { // Injected here
this.repository = repository;
}
}
3.Constructor Injection => Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Autowired annotation is optional.
Example:
public class MyService {
private final MyRepository repository;
public MyService(MyRepository repository) { // Injected here
this.repository = repository;
}
}

Annotations Learnt:
1.Controller:
Marks a class as a Spring MVC controller. It is typically used in applications that return a View (like a Thymeleaf or JSP page).

2.ResponseBody:
We can use the @ResponseBody annotation on a method to have the return serialized(Java Object to Json/XML format) to the response body through an HttpMessageWriter(Contract to Decode HTTP Content).

3.RestController:
Acts as a request handler that returns data (typically JSON or XML) directly to the client instead of rendering a view like an HTML template.It is combination of @Controller and @ResponseBody

4.RequestMapping:
We can use this annotation to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. You can use it at the class level to express shared mappings or at the method level to narrow down to a specific endpoint mapping.There are also HTTP method specific shortcut variants of RequestMapping as follows
1.GetMapping(To read data)
2.PutMapping(To update existing data)
3.PostMapping(To create new data)
4.DeleteMapping(To delete data)

5.ResponseBody:
This annotation tells the springboot application to accept the return data as page content rather than being interpreted as a view name (like an HTML template).

5.PathVariable:
Its the Annotation which indicates that a method parameter should be bound to a URL variable. Supported for RequestMapping annotated handler methods.
We have to give param name inside curly braces in Requestmapping to say sprinboot that its a variable name.
Example:
@GetMapping("/foos/{id}")
@ResponseBody
public String getLoginId(@PathVariable String id) {
return "ID: " + id;
}

6.RequestParam:
RequestParam is also used to extract values from URL as same as PathVariable but it is slightly different from PathVariable. In this annotation we dont need to represent variable name in requestmapping we can directly give as parameter in method itself.
Example:
@GetMapping("/login")
@ResponseBody
public String getLoginId(@RequestParam String id) {
return "ID: " + id;
}

7.RequestBody:
This annotation is primarily used in Spring Boot and Spring MVC to bind the body of an incoming HTTP request to a method parameter in a REST controller. It is inverse of Responsebody i.e it Deserialize(Json/XML to Java Object) the incoming request to process the data.

8.Autowired:
An important Annotation which enables the core concept(Dependency Injection) of spring boot. This annotation let know the spring boot for which class bean to be created and to which class created bean needs to be injected. Note: It is not mandatory for constructor injection

  1. Data: It is the Annotation which is available from Lombok dependency. It enables developers to create getters and setters easily for all the variables in a class.

Logging:
Logging is a message that is printed in a console for each and every activities performed by a springboot application which enable us to undestand the internal working(behind the scene). It helps us to narrow down the issue and debug efficiently. We can also print those logging in file if we want. There are multiple levels of logging we can use it as per our needs
1.Trace (The most fine-grained level, capturing detailed execution traces of the application.)
2.Debug (Informational events that are most useful to debug an application.)
3.INFO (The default level for Spring Boot. It highlights the progress of the application at a coarse-grained level.)
4.Warn ( Indicates potentially harmful situations or unexpected behavior that do not necessarily stop the application.)
5.Error (Records significant failures where the application may still run but a specific operation failed (e.g., database query failure).)

         To use Logging feature we have to give **logging.level.root = error/debug/info/trace** in application.properties file to print all the messages in root level(all applications)
          To use logging feature at our application level we have to give **logging.level.package(in which our application present) = root/erroe/debug/info/trace**
Enter fullscreen mode Exit fullscreen mode

Top comments (0)