Stereotype Annotations

Stereotype Annotations

Spring Boot provides stereotype annotations to mark classes as Spring-managed components, making them easier to detect and manage in the Spring container. These annotations are used to define specialized beans with specific roles in a Spring application.



1. @Component

    import org.springframework.stereotype.Component;
    @Component
    public class MyComponent {
        public void doSomething() {
            System.out.println("Doing something...");
        }
    }                
            


2. @Service

    import org.springframework.stereotype.Service;
    @Service
    public class MyService {
        public String getServiceName() {
            return "My Business Service";
        }
    }                   
            


3. @Repository

    import org.springframework.stereotype.Repository;
    @Repository
    public class MyRepository {
        public void saveData(String data) {
            System.out.println("Saving data: " + data);
        }
    }
                                   
            


4. @Controller/ @RestController

    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.GetMapping;              
    @RestController
    public class MyRestController {              
        @GetMapping("/api/data")
        public String getData() {
            return "This is data from REST API";
        }
    }                
            

@PostConstruct


@PreDestroy


@Configuration

A @Configuration class is a special type of Spring component that is used to define Spring beans through methods annotated with @Bean. This approach allows you to configure your application using Java code instead of XML. A @Configuration class can also include other configuration classes and allow for component scanning.


    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    public class AppConfig {
        @Bean
        public MyService myService() {
            return new MyService();
        }
    }