Comprehensive Guide to Spring Boot Annotations
This article provides a detailed overview of common Spring Boot annotations, their purposes, usage examples, and related code snippets, helping developers understand how to configure and build RESTful Java applications efficiently.
1. Annotation List
@SpringBootApplication: Combines @ComponentScan, @Configuration, and @EnableAutoConfiguration. @ComponentScan enables Spring Boot to discover @Configuration classes and add them to the application context.
@Configuration: Equivalent to a Spring XML configuration file; using Java code ensures type safety.
@EnableAutoConfiguration: Enables automatic configuration based on classpath dependencies.
@ComponentScan: Scans for components such as @Component, @Service, @Repository, and registers them as beans.
@Component: Can be used with CommandLineRunner to execute tasks after application startup.
@RestController: A combination of @Controller and @ResponseBody, indicating a controller bean whose method return values are written directly to the HTTP response body (REST style).
@Autowired: Automatic injection of dependent beans.
@PathVariable: Retrieves variables from the URL path.
@JsonBackReference: Solves nested reference problems during JSON serialization.
@RepositoryRestResource: Used together with spring-boot-starter-data-rest.
2. Detailed Annotation Explanation
@SpringBootApplication declares that Spring Boot should automatically configure the application, equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan together.
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}@ResponseBody indicates that the method's return value is written directly to the HTTP response body, commonly used for asynchronous data retrieval such as returning JSON.
@RequestMapping("/test")
@ResponseBody
public String test(){
return "ok";
}@Controller defines a controller class that forwards incoming URL requests to corresponding service layer methods.
@Controller
@RequestMapping("/demoInfo")
public class DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
// The view resolver will render hello.html or hello.ftl
return "/hello";
}
}@RestController is a shortcut for @Controller combined with @ResponseBody.
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/demoInfo2")
public class DemoController2 {
@RequestMapping("/test")
public String test(){
return "ok";
}
}@RequestMapping provides routing information, mapping URLs to specific controller methods.
@EnableAutoConfiguration attempts to automatically configure the Spring application based on the JAR dependencies present on the classpath.
@ComponentScan automatically discovers beans annotated with @Component, @Service, @Repository, etc., within the package of the main class and its sub‑packages.
@Configuration serves as a Java‑based replacement for XML configuration files; @ImportResource can be used to load XML files when needed.
@Import imports other configuration classes.
@ImportResource loads XML configuration files.
@Autowired performs automatic dependency injection.
@Service marks a class as a service‑layer component.
@Repository ensures DAO or repository classes are discovered and provides exception translation.
@Bean declares a method that produces a bean, similar to an XML definition.
@Value injects property values from application.properties or other property sources.
@Value(value = "#{message}")
private String message;@Inject is equivalent to @Autowired but without the required attribute.
@Component is a generic stereotype for any Spring-managed component.
@Qualifier specifies which bean to inject when multiple candidates of the same type exist.
@Autowired
@Qualifier(value = "demoInfoService")
private DemoInfoService demoInfoService;@Resource(name="name", type="type") performs injection by name (default) and can also be used similarly to @Autowired.
3. JPA Annotations
@Entity and @Table(name=""): Mark a class as a JPA entity; @Table can be omitted if the table name matches the class name.
@MappedSuperclass: Indicates that a class provides mapping information for its subclasses.
@NoRepositoryBean: Marks a repository interface as a base class that Spring should not instantiate.
@Column: Maps a field to a database column; can be omitted if names match.
@Id: Denotes the primary key field.
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "repair_seq"): Configures sequence‑based primary key generation.
@SequenceGenerator(name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1): Defines a database sequence.
@Transient: Indicates that a field is not persisted to the database.
@JsonIgnore: Excludes a property from JSON serialization and deserialization.
@JoinColumn(name="loginId"): Specifies a foreign key column for one‑to‑one or many‑to‑one relationships.
@OneToOne, @OneToMany, @ManyToOne: Define relationship cardinalities in JPA.
4. Spring MVC Annotations
@RequestMapping("/path") maps a controller or method to a specific URL path and can be applied at class or method level.
The annotation has six attributes: params, headers, value, method, consumes, and produces, which control request matching and content negotiation.
@RequestParam is used on method parameters to bind request parameters.
@RequestParam
String a = request.getParameter("a");@PathVariable binds a URI template variable to a method parameter.
@RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
// do something
}5. Global Exception Handling
@ControllerAdvice, which includes @Component, is scanned and used for centralized exception handling.
@ExceptionHandler(Exception.class) placed on a method handles the specified exception type.
Source: cnblogs.com/tanwei81/p/6814022.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
