0% found this document useful (0 votes)
10 views

spring

The document provides an overview of various Spring and Spring Boot annotations, detailing their purposes and examples of usage. It categorizes annotations into sections such as Spring Annotations, Spring Boot Annotations, Spring Boot Specific Annotations, and Spring Boot Testing Annotations. Each annotation is accompanied by a brief description and a code example to illustrate its application.

Uploaded by

Debasis Bhuyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

spring

The document provides an overview of various Spring and Spring Boot annotations, detailing their purposes and examples of usage. It categorizes annotations into sections such as Spring Annotations, Spring Boot Annotations, Spring Boot Specific Annotations, and Spring Boot Testing Annotations. Each annotation is accompanied by a brief description and a code example to illustrate its application.

Uploaded by

Debasis Bhuyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Spring Annotations
Annotation Purpose Example

@Component Marks a class as a Spring-managed java @Component public class Car { private

bean for dependency injection. Engine engine; @Autowired public Car(Engine


engine) { this.engine = engine; } }

@Service Specialization of @Component for java @Service public class OrderService {

service-layer beans. public void processOrder() { // logic } }

@Repository Specialization of @Component for java @Repository public class UserRepository {

DAO (Data Access Object) beans. public void save(User user) { // logic } }

@Controller Marks a class as a Spring MVC java @Controller public class UserController {

controller (handles HTTP requests). @GetMapping("/user") public String getUser() {


return "user"; } }

@RestController A combination java @RestController public class

of @Controller and @ResponseBody , UserController { @GetMapping("/user") public


User getUser() { return new User("John",
used to create RESTful APIs.
"[email protected]"); } }

@Autowired Automatically injects dependencies java @Autowired private Engine engine;

into fields, constructors, or setters.

@Qualifier Specifies which bean to inject when java @Autowired @Qualifier("electricEngine")

there are multiple candidates. private Engine engine;

@Value Injects property values into fields or java @Value("${app.name}") private String

methods. appName;

@PostConstruct Marks a method to be run after java @PostConstruct public void init() { //

dependency injection and before the Initialization logic }

bean is used.

@PreDestroy Marks a method to be run before the java @PreDestroy public void cleanup() { //

bean is destroyed. Cleanup logic }

@RequestMapping Maps HTTP requests to handler java @RequestMapping("/users") public String

methods of MVC and REST getUsers() { return "userList"; }

controllers.

@GetMapping A shortcut java @GetMapping("/user/{id}") public User

for @RequestMapping(method = getUser(@PathVariable String id) { return


userService.getUser(id); }
RequestMethod.GET) .

@PostMapping A shortcut java @PostMapping("/user") public void

for @RequestMapping(method = createUser(@RequestBody User user) {


userService.createUser(user); }
RequestMethod.POST) .

@PutMapping A shortcut java @PutMapping("/user/{id}") public void

for @RequestMapping(method = updateUser(@PathVariable String id,


@RequestBody User user) {
RequestMethod.PUT) .
userService.updateUser(id, user); }

@DeleteMapping A shortcut java @DeleteMapping("/user/{id}") public void

for @RequestMapping(method = deleteUser(@PathVariable String id) {


Annotation Purpose Example

RequestMethod.DELETE) . userService.deleteUser(id); }

@RequestParam Binds request parameters to method java @GetMapping("/user") public User

parameters in controller methods. getUser(@RequestParam("id") String id) {


return userService.getUser(id); }

@PathVariable Binds path variables to method java @GetMapping("/user/{id}") public User

parameters. getUser(@PathVariable String id) { return


userService.getUser(id); }

@ResponseBody Indicates that the return value of a java @RequestMapping("/user") @ResponseBody

method should be bound to the web public User getUser() { return


userService.getUser(); }
response body.

@ExceptionHandler Used to handle exceptions in Spring java

MVC controllers. @ExceptionHandler(UserNotFoundException.class)


public String
handleUserNotFound(UserNotFoundException ex) {
return "User not found"; }

@CrossOrigin Enables cross-origin resource sharing java @CrossOrigin(origins =

(CORS) on controller methods or "http://example.com") @GetMapping("/user")


public User getUser() { return
classes.
userService.getUser(); }

2. Spring Boot Annotations


Annotation Purpose Example

@SpringBootApplication A convenience annotation that java @SpringBootApplication public class

combines @Configuration , @EnableAutoConfiguration , Application { public static void


main(String[] args) {
and @ComponentScan .
SpringApplication.run(Application.class,
args); } }

@EnableAutoConfiguration Enables Spring Boot’s auto-configuration mechanism. java @EnableAutoConfiguration public


class Application { public static void
main(String[] args) {
SpringApplication.run(Application.class,
args); } }

@Configuration Indicates that the class contains Spring configuration. java @Configuration public class
AppConfig { @Bean public DataSource
dataSource() { return new DataSource();
} }

@Bean Indicates that a method produces a bean to be java @Bean public DataSource

managed by the Spring container. dataSource() { return new DataSource();


}

@EnableScheduling Enables Spring's scheduled task execution capability. java @EnableScheduling


@SpringBootApplication public class
Application { @Scheduled(fixedRate =
Annotation Purpose Example
5000) public void scheduledTask() { //
Task logic } }

@Scheduled Marks a method to be executed periodically based on java @Scheduled(cron = "0 0 * * * ?")

cron expressions or fixed rates. public void hourlyTask() { // logic }

@Profile Indicates that a bean is available only for a specific java @Profile("dev") @Bean public

profile (e.g., dev , prod ). DataSource dataSource() { return new


DevDataSource(); }

@ComponentScan Specifies the packages to scan for Spring beans (if not java @ComponentScan(basePackages =

using the default package). "com.example") public class AppConfig {


}

@Value Injects values from application properties into fields. java @Value("${app.name}") private
String appName;

@SpringBootTest Indicates that a test class is a Spring Boot test, running java @SpringBootTest public class

with the application context. ApplicationTests { @Test public void


contextLoads() { } }

3. Spring Boot Specific Annotations (Application Properties)


Annotation Purpose Example

@PropertySource Specifies the java

location of @PropertySource("classpath:application.properties")
public class AppConfig { }
property files
to be used
by the
application.

@EnableConfigurationProperties Binds java

properties @EnableConfigurationProperties(AppConfig.class)
public class Application { }
from
configuration
files to a
Spring bean.

@ConfigurationProperties Binds a class java @ConfigurationProperties(prefix = "app")

to a public class AppConfig { private String name; }

configuration
properties
file.

4. Spring Boot Testing Annotations


Annotation Purpose Example

@SpringBootTest Runs the application java @SpringBootTest public class ApplicationTests {

context for integration @Test public void contextLoads() { } }

tests.

@MockBean Creates a mock bean java @MockBean private UserService userService;

and replaces the


existing bean in the
application context.

@Test Marks a method as a java @Test public void testUserService() { // test logic

test method in Spring }

Boot test classes.

@AutoConfigureMockMvc Configures MockMvc for java @AutoConfigureMockMvc public class

testing Spring MVC UserControllerTest { @Test public void


testUserController() {
controllers.
mockMvc.perform(get("/user")).andExpect(status().isOk());
} }

You might also like