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
- The generic stereotype annotation that marks a class as a Spring Bean.
- Spring automatically detects classes annotated with @Component and registers them as beans.
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
public void doSomething() {
System.out.println("Doing something...");
}
}
2. @Service
- The @Service annotation is typically applied to classes in the service layer, where business logic is implemented and external API calls are handled.
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String getServiceName() {
return "My Business Service";
}
}
3. @Repository
- The @Repository annotation is used for classes that manage database operations, such as insert, update, delete, and query actions.
import org.springframework.stereotype.Repository;
@Repository
public class MyRepository {
public void saveData(String data) {
System.out.println("Saving data: " + data);
}
}
4. @Controller/ @RestController
- @Controller is used in Spring MVC to define classes that handle HTTP requests and return views (like JSP or Thymeleaf).
- @RestController is a specialized version of `@Controller` that combines `@Controller` and `@ResponseBody`, and is used to handle RESTful web services, returning data directly in JSON or XML format instead of views.
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
@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();
}
}