2. Spring Annotation

 Basic Spring Interview Question 


1. @Component Annotation 

-  @Component is a class-level annotation.

 @Component is used for declaring a Java class as a Spring component.

- @Component is a stereotype annotation that marks a class as a Spring bean, making it eligible for autodetection and automatic registration in the application context. It's a fundamental annotation in Spring that enables loose coupling and modular architecture.

- It's a powerful annotation that simplifies the registration process and allows for easy dependency injection.

- @Component is a core annotation in Spring used for marking a class as a Spring component, allowing it to be managed by the Spring IoC container. It plays a crucial role in enabling dependency injection and the inversion of control mechanism provided by the Spring Framework.

- The @Component annotation tells Spring container to create Spring bean automatically. So we don't have to create object manually Spring IoC container take care of creating & Managing object of Class.


Ex :

@Component

public class UserService {

    // ...

}


--

@RestController

public class UserController {

    @Autowired

    private UserService userService;

    // ...

}



Types of Configuration in Spring 

1. XML Base Conf 2. Annotation Based Conf 3. Java Based Confi



2. @Autowired Annotation

- The @Autowired annoatation is used to inject(wire) dependency into spring bean automatically. 

- The @Autowired annotation has simplified the code and reduced the boilerplate code significantly.

- There are different autowiring type like  byType, byName, constructor.

- The @Autowired annoatation is used to inject depedency using  constructor injection, setter injection and field injection.(non-setter methods and properties.)



3. @Qualifier: 

- If there are multiple beans of same type and spring get confuse that time which one bean exact have to  inject then remove that confusion we can @Qualifier Annotation. 

-   @Qualifier: This Spring Framework annotation along with the @Autowired is used for removing the confusion when two or beans configured for same type.

Optional Dependency: By default, @Autowired requires a matching bean to be found. If no matching bean is found, it throws an exception. However, you can make the dependency optional by using @Autowired(required = false).


4. @Primary Annoation 

- @Primary above the class declaration of a bean to mark it as the primary bean of that type.

-  @Primary Annotation used to give higher preference to a bean when there are multiple beans of the same types in spring Application Context. 

- Instead of Qualifier we can primary to give higher preference.



5. @Bean Annotaion

Bean is a very commonly used annotation in Spring framework.

- The @Bean annotation in Java is used in the Spring framework to define and register a bean (a Spring-managed object) within a Spring application context.
- Creates and registers a Spring bean
- Defines a factory method for creating the bean

-  It’s a method-level annotation, which indicates that the annotated method produces a bean to be managed by the Spring container. 

    - A Spring bean is a Java object managed by Spring’s IoC (Inversion of Control) container and it can be used by other objects via dependency injection.

- @Bean annotation is used to declare a method as a bean.IoC will managed all life cycle of Bean.

- @Bean Annotaion indicated that a method produces a bean to be managed by the Spring container. The @Bean Annotaion is usaually declared in Configuration class to crete Bean definitions. 

- By default , the bean name is same as method name. We can specify bean name using @Bean(name="beanName).

- @Bean annotation provides initMethod() and destroyMethod() attribute to perform certain action after bean initailization or before bean destruction by a container.

PostConstruct annotation is commonly used to perform initialization tasks such as setting up resources, establishing connections, or initializing variables.

@PreDestroy: (usually when the application context is shutting down),  annotation is commonly used to release resources, close connections, or perform cleanup tasks before the bean is destroyed.


- Using @PostConstruct and @PreDestroy annotations allows you to handle bean initialization and destruction in a standardized and convenient way, ensuring that your beans are properly initialized and cleaned up throughout the lifecycle of your Spring Boot application.




4.  @Import Annotation : 

- The @Import annotation is used to import other Spring configuration classes into your current configuration class.

-  use of @Import above your configuration class and specify one or more classes to import.


Ex :

@Configuration @Import({ServiceConfig.class, RepositoryConfig.class}) public class AppConfig { // Configuration class implementation }


{ Stereotype annotations are special annotations that define a class's role in a Spring application.}

5. Stereotype Annoatations.

- The Annotaion are used to create bean automatically in the application context(Spring IOC Container).

- The main stereotype annotation is @Component

- By Using this annotation , Spring provides more Stereotype meta annoatation such as @Service , @Repository and @Controller.

1.@Service

        -  The @Service annotation use to mark a class as a service. 

        - It's a specialization of the @Component annotation.

        -  @Service annotation Indicate that annoatated class is  Service which implement the business logic for perticular domain of application. 

        - Service components are commonly used to implement business logic, perform database operations, coordinate transactions, or interact with external systems.

2. @Repository  : 

    -  @Repository is a class-level annotation indicates that an annotated class is a “Repository”. 

    - A repository class should implement code relates to persistent layer or DAO (Data Access Objects) of a specific domain .

    - Purpose of using @Repository annotation: specify the role of a class as a repository, which encapsulates code of persistence/DAO layer for a specific business domain.

    - The repository annotation indicates the class has the capability of storage, retrieval, updating, deletion, and search.


3. @Controller        -

        - @Controller is class level Annotation.

        - The annotation is used to indicate that the class is a web controller or we can  say web request handler. It is often used to present web pages. It is most commonly used with @RequestMapping annotation.

        - The @Controller annotation indicates that the class serves the controller role, playing a pivotal important role in handling web requests. 

- Controller in Spring MVC Web application is component that handles incoming HTTP requests.

- @Controller annotation is simply a specialization of the @Component class, which allows us auto-detect implementation classes throught the classpath scanning.

- we typically use @Controller in combination with a @RequestMapping annotation for request handling methods.


Below is a table of differences between controller and restcontroller.

Aspect

@Controller

@RestController

Annotation Type

A stereotype annotation used in Spring MVC to define a class as controller component.

@RestController annotation is a special controller used in RESTful Web services, and it’s the combination of @Controller and @ResponseBody annotation.

Purpose

Primarily used for traditional web applications to return a view.

Used for building RESTful web services, returning data in JSON or XML format.

ResponseBody

Requires @ResponseBody annotation on the method to serialize the return object to the HTTP response body.

Automatically serializes return objects to the HTTP response body because it includes @ResponseBody.

View Resolution

Supports view resolution, allowing for returning a view name which will be resolved by a ViewResolver.

Does not support view resolution. Designed to return data directly to the client.

Use Case

Suited for applications that return HTML or JSP pages.

Suited for API development where the response is data (e.g., JSON, XML).

Content Type

Can produce any type of content, including HTML, but requires explicit annotation to return data as JSON or XML.

Primarily produces JSON or XML responses.

Headers

You have to manually add @ResponseBody for it to include relevant headers indicating the type of response.

Automatically handles and includes headers indicating the type of response (e.g., application/json).

@Controller added to Spring 2.5 version. where @RestController added to Spring 4.0 version.


 

6. @Lazy Annotation

-  By default , Spring create all singleton bean eagerly at the startup of the application context.

- You can load spring beans lazily (on demand) using @Lazy Annotation.

- @Lazy Annotation can used with @Configuration, @Component , @Bean Annotations.

- @Lazy annotation is used to indicate that a bean should be lazily initialized. This means that the bean will not be created until it is first requested, rather than being created eagerly during the application startup. 

  -  Lazy initialization can be useful for optimizing performance, especially for beans that are not always needed or are resource-intensive to create.

- Eager initialization is recommended : to avoid and detect all posible errors immediately rather than at runtime.


7. @Value Annotation

- Spring @Value Annotation  is used for to asign default values to varible and method arguments.

        - This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.

- @Value Annotation is mostly used to get value for specific property key from the properties file.

- We can read spring environment varible as well as System variable using @Value Annotation.

        -  We can  inject values into Spring beans from externalized sources such as properties files, environment variables, or system properties.

        - Ex @Value("${my.property}")


8. @PropertySource Annotation

   - The @PropertySource annotation in Java is used in the Spring framework to specify the location of a properties file that contains key-value pairs to be injected into a Spring application context

        - Spring @PropertySource Annotation is used to provide properties file to Spring Environment.

- Spring @PropertySource Annotation is used to provide multiple properties files to spring environment.

- These annotation is used with @Configuration clasess.

- Spring @PropertySource Annotation is repeatable , means you can have multiple PropertySource on a Configuration class.

- We can use @Value annotation and Environment class to read the Property file. 


@Configuration

@PropertySource("classpath:application.properties")

public class MyConfig {

  

  @Value("${my.property}")

  private String myProperty;

  

  // ...

}


9. @Configuration Annotation

- It is a class-level annotation.

 - we Use the @Configuration annotation to indicate that the annotated class declares one or more @Bean methods and that can be used to configure the Spring Container.  

        -It also Indicates that a class contains bean definitions and configuration for the Spring application context.

    

    - Spring Bean Scopes 

-1. singleton 2. prototype

- 3. request , 4. session 4. application , 5. websocket last four only available for web-aware application.


10. @Scope Annotation 

- @Scope Annotation is used to define scope of bean.

- We use @Scope to define the scope of a @Component class or @Bean definition.

1. Singleton : Only one instace of the bean is created and shared across the entire application. This is the default scope.

2. Prototype : a new instance of the bean is created every time it is requested .



11. @RequestMapping

- @RequestMapping annotation is used to map web request to Spring Controller methods.

        - RqeustMapping use with the class as well as the method.

- RequestMapping is used to map the HTTP request.  It has many other optional elements like name, method, request, path,consumes,  etc.

- @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

- @RequestMapping Annotation Examples

1.@RequestMapping with Class

2.@RequestMapping with Method

3.@RequestMapping with Mupltiple URI

4.@RequestMapping with HTTP Method

5. @RequestMapping with Produces and Consumes.




12. @RestController Annotation

        - We use the @RestController annotation to develop RESTful Webservices, i.e. web controllers that read/write JSON/XML data based on standard HTTP methods (GET, POST, PUT, DELETE…).

       In Order to develop RESTFul web services using spring MVC we need to use @Controller and @ResponseBody annotation.

- Spring 4.0 introduced @RestController , a specialized version of the @Controller which is a convenience annotation that does nothing more than adding the @Controller and @ResposeBody annotations.


Best Cases:

-  @Controller for server-side rendering of views and @RestController for building RESTful APIs.

- Use @Controller when building web applications where you need to render HTML views and handle form submissions.

- Use @RestController when developing RESTful APIs to provide data to other applications, like single-page applications, mobile apps, or microservices, where responses are typically in JSON or XML format.




REST Web Service Annotation 


13. @GetMapping Annotation

- The GET HTTP request is used to get a single or multiple resources and @GetMapping annotation for mapping HTTP GET request onto specific handler method.

- Specifically , @GetMapping  is composed annotation that acts as a shortcut for @GetMapping(method = RequestMethod.GET).




14. @PostMapping and @RequestBody Annotation

1. The POST HTTP method is used to create a resource and @PostMapping annotation for mapping HTTP POST requests onto specific handler method.

2. Specifically, @PostMapping is composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

3. The @RequestBody annotation is Responsible for retrieving the HTTP request body and automatically converting it to the java object.



15. @PutMapping Annotation

1. The PUT HTTP method is used to update the resource and @PutMapping annotation for Mapping HTTP PUT request onto specific handler method.

2. Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).



16. @DeleteMapping Annotation 

1. The DELETE HTTP method is used to delete the resource and @DeleteMapping annotation for mapping HTTP DELETE request onto specific handler methods.

2. Specifically , @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(Method = RequestMethod.DELETE).



17. @PathVariable 

- @PathVariable is used to bind a method parameter to a path variable. It's often used in RESTful web services where the URL contains a path variable.

       - @PathVariable is used  to Extracts values from the URL path and maps them to method parameters in Spring MVC controllers.

-  Dynamic URL Segments: Path variables are dynamic segments of a URL path enclosed within curly braces {}. They can represent various data such as IDs, names, or any other parameters.



18. @RequestParam Annotation

        - @RequestParam used to  Extracts request parameters from the URL query string and maps them to method parameters in Spring MVC controllers.

        - Request parameters are key-value pairs sent with an HTTP request. They can be included in the URL query string (e.g., /endpoint?param1=value1&param2=value2) . 

       

@RequestMapping("/hello") 

public String sayHello(@RequestParam("name") String name) 

{

 return "Hello, " + name + "!"; 

}

Difference between @RequestParam / @QueryParam  and @PathVariable / @PathParam

@RequestParams capture(extract) query parameter from the query of http request, @PathVariables capture(extract) values from the URL path.

- When we want fetch only  unique element from then we can use @Pathvarible and we want fetch multiple  data then we can use     @Queryparam .  



When to USE ?
- Use @RequestParam when the parameter is optional, or you need to handle complex scenarios with default values or not strictly tied to a URI structure.

- Use @PathVariable for required parameters that are a natural part of the URI and when you're modeling RESTful endpoints.


19. SpringBootApplication 

- SpringBootApplication  = (@SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan() )


20. @ConfigurationProperties Annotation 

- @CngigurationProperties  bind external configuration to a strongly typed in your application code. You can inject and use this bean throughout your application code just like any other spring bean.

- Spring Boot has many useful features including externalized configuration and easy access to properties defined in properties files.

- Spring will automatically bind any property defined in our property file that has the prefix mail and the same name as one of the fields in the ConfigProperties class.


-Nested Properties 

We can have nested properties in Lists, Maps, and Classes.



@Configuration

@ConfigurationProperties(prefix = "mail")

public class ConfigProperties {

    

    private String hostName;

    private int port;

    private String from;


    // standard getters and setters

}


Note: If we don’t use @Configuration in the POJO, then we need to add @EnableConfigurationProperties(ConfigProperties.class) in the main Spring application class to bind the properties into the POJO:


@SpringBootApplication

@EnableConfigurationProperties(ConfigProperties.class)

public class EnableConfigurationDemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(EnableConfigurationDemoApplication.class, args);

    }

}


Spring will automatically bind any property defined in our property file that has the prefix mail and the same name as one of the fields in the ConfigProperties class.




Comments

Popular posts from this blog

Core Java Interview Question

1. Collection Framework all in one

4. Real-Time Spring boot Interview Question (GenZ Career)