Spring Framework Annotations
The Spring Framework annotations are used extensively to configure, define, and manage various components, behaviors, and services within a Spring-based application. These annotations simplify Java configuration, reducing the need for XML-based configuration files and making the code more concise, readable, and maintainable.
commonly used annotations in the Spring Framework:
1. Core Annotations for Spring Beans
@Component: use it as a class for a spring component (a spring-managed bean).
Example
@Component
public class MyService {
public void execute() {
// business logic
}
}
@Service: A specialization of @Component, typically used for service-layer beans (business logic).
@Service
public class UserService {
public void createUser() {
// user creation logic
}
}
@Repository: A specialization of @Component, typically used for DAO (Data Access Object) beans, to indicate that the class is responsible for database operations.
@Repository
public class UserRepository {
public User findUserById(int id) {
// database query logic
}
}
@Controller: A specialization of @Component, used to define controllers in Spring MVC applications (handling web requests).
@Controller
public class UserController {
@RequestMapping(“/users”)
public String getUsers() {
return “users”;
}
}
@Configuration: Indicates that a class contains Spring bean definitions, and it can be used as a replacement for XML configuration. This class can include @Bean methods to define beans. @Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Bean: Defines a bean within a @Configuration class. It shows that the method will return a Spring-managed bean.
@Configuration public class AppConfig {
@Bean public MyService myService()
{
return new MyService();
}
}
2. Dependency Injection Annotations
@Autowired: Automatically wires a bean into another bean by type. If there are multiple candidates, Spring will inject the one that matches the required type.
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void createUser() {
userRepository.save(new User());
}
}
@Value: Injects values into fields from properties files or expression languages. @Value(“${app.name}”)
private String appName;
3. Spring MVC Annotations
For web applications, Spring MVC provides annotations to manage request handling, data binding, and more
@RequestMapping: Defines the URL mapping for a method or class in a controller. It handles different HTTP methods (GET, POST, etc.).
- Example:
@RequestMapping(“/home”)
public String homePage() {
return “home”;
}
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Specializations of @RequestMapping for different HTTP methods.
o Example:
@GetMapping(“/users”)
public List getUsers() {
return userService.findAllUsers();
}
@PathVariable: Used to bind a method parameter to a URI template variable. o Example:
@GetMapping(“/user/{id}”)
public User getUser(@PathVariable(“id”) int id) {
return userService.getUserById(id);
}
@RequestParam: Binds request parameters to method parameters in the controller. o Example:
@GetMapping(“/search”)
public String search(@RequestParam(“query”) String query) {
return query;
}
@ResponseBody: Indicates that the return value of a method should be written directly to the HTTP response body (usually in JSON or XML format).
o Example:
@GetMapping(“/users”)
@ResponseBody
public List getUsers() {
return userService.findAllUsers();
}
@RestController: A convenience annotation that combines @Controller and @ResponseBody, so that all methods in the class return data directly to the HTTP response body.
o Example:
@RestController
public class UserController {
@GetMapping(“/users”)
public List getUsers() {
return userService.findAllUsers();
}
}
4. Transactional Annotations
These annotations are used to manage transactions in Spring.
@Transactional: Indicates that a method or class should be executed within a transactional context. It manages the commit and rollback automatically.
o Example:
@Transactional
public void createUser(User user) {
userRepository.save(user);
}
5. AOP (Aspect-Oriented Programming) Annotations
Spring provides annotations for Aspect-Oriented Programming, allowing you to define cross-cutting concerns like logging, security, and transaction management.
@Aspect: Marks a class as an aspect (a class that defines cross-cutting concerns). o Example:
@Aspect
@Component
public class LoggingAspect {
@Before(“execution(* com.example.service.*.*(..))”)
public void logBeforeMethod() {
System.out.println(“Method executed”);
}
}
@Before, @After, @Around: These annotations define advice that can be applied before, after, or around method executions.
o Example (for logging):
@Before(“execution(* com.example.service.*.*(..))”)
public void logBeforeMethod() {
System.out.println(“Before method execution”);
}
For Free, Demo classes Call: 020-71173125
Registration Link: Java Training in Pune!
6. Test Annotations
Spring also has several annotations to support testing.
@SpringBootTest: this annotation is Used to make an application context for testing. o Example:
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testService() {
assertNotNull(myService);
}
}
@MockBean: Used to mock beans in the Spring context, often used in integration tests. o Example:
@MockBean
private UserRepository userRepository;
@RestController
A specialized version of @Controller is used for RESTful web services. It combines @Controller and @ResponseBody, which means it automatically serializes returned objects into JSON or XML.
@RestController
public class MyRestController {
@GetMapping(“/greet”)
public String greet() {
return “Hello, World!”;
}
}
Spring Framework annotations provide a powerful, declarative way to configure and manage beans, handle dependencies, define web request mappings, and more. They reduce the amount of boilerplate code and configuration needed in a Spring application, making it more concise and easier to maintain. By leveraging annotations like @Component, @Autowired, @RequestMapping, and @Transactional,
developers can easily implement the core principles of dependency injection, aspect-oriented programming, and transaction management within their Spring applications.
Do visit our channel to know more: Click Here
Author:-
Pooja Ghodekar
Call the Trainer and Book your free demo Class For Java Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.