Master Spring Boot Annotations: A Complete Guide to Backend Development
This article provides a comprehensive overview of Spring Boot, Spring MVC, and JPA annotations, explaining their purposes, usage patterns, and example code snippets, while also covering global exception handling with @ControllerAdvice and @ExceptionHandler for robust backend development.
1. Annotation List
@SpringBootApplication combines @ComponentScan, @Configuration and @EnableAutoConfiguration, allowing Spring Boot to automatically configure the application.
@Configuration is equivalent to an XML configuration file, offering type‑safe Java‑based configuration.
@EnableAutoConfiguration enables Spring Boot's auto‑configuration mechanism.
@ComponentScan scans for components such as @Component, @Controller, @Service, and registers them as beans.
@Component can be used with CommandLineRunner to execute tasks after startup.
@RestController is a combination of @Controller and @ResponseBody, defining a REST‑style controller.
@Autowired injects dependencies automatically.
@PathVariable binds URL path variables to method parameters.
@JsonBackReference resolves circular reference issues during JSON serialization.
@RepositoryRestResource works with spring‑boot‑starter‑data‑rest.
2. Annotation Details
@SpringBootApplication declares that Spring Boot should perform necessary configuration, equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan together.
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 writes the method return value directly to the HTTP response body, useful for returning JSON data in RESTful APIs.
@RequestMapping("/test")
@ResponseBody
public String test() {
return "ok";
}@Controller defines a controller class; its methods are typically mapped with @RequestMapping.
@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");
return "/hello";
}
}@RestController combines @Controller and @ResponseBody.
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 controller methods.
@EnableAutoConfiguration attempts to configure the application based on the classpath, e.g., automatically configuring an in‑memory database if HSQLDB is present.
@ComponentScan automatically discovers beans annotated with @Component, @Controller, @Service, 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 load XML files when needed.
@Import imports other configuration classes.
@ImportResource loads XML configuration files.
@Autowired injects dependent beans by type, optionally with @Qualifier to resolve ambiguity.
@Service marks a service‑layer component.
@Repository enables exception translation for DAO or repository classes.
@Bean declares a method that produces a bean, similar to XML bean definitions.
@Value injects property values from application.properties.
@Value("#{message}")
private String message;@Inject is equivalent to @Autowired without the required attribute.
@Component is a generic stereotype for components that do not fit other specific stereotypes.
@Autowired (also written as @AutoWired) performs automatic dependency injection; with required=false it tolerates missing beans.
@Qualifier specifies which bean to inject when multiple candidates exist.
@Autowired
@Qualifier("demoInfoService")
private DemoInfoService demoInfoService;@Resource(name="name", type="type") injects by name (default) or by type, similar 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 designates a superclass whose properties are inherited by entity subclasses.
@NoRepositoryBean indicates that a repository interface should not be instantiated directly.
@Column maps a field to a database column; it can be omitted when names match.
@Id marks the primary‑key field.
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "repair_seq") defines a sequence‑based primary‑key generation strategy.
@SequenceGenerator(name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1) configures the sequence details.
@Transient excludes a field from persistence mapping.
@JsonIgnore prevents a property from being serialized or deserialized in JSON.
@JoinColumn(name="loginId") defines a foreign‑key column for one‑to‑one or one‑to‑many relationships.
@OneToOne , @OneToMany , @ManyToOne map entity relationships as defined in Hibernate.
4. Spring MVC Annotations
@RequestMapping ("/path") maps a controller or method to a specific URL and can specify parameters, headers, HTTP method, consumes, and produces attributes.
@RequestParam binds request parameters to method arguments.
@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 is a component that provides centralized exception handling across all controllers.
@ExceptionHandler(Exception.class) marks a method to handle specific exception types.
Source: https://blog.csdn.net/zhanglong_4444/article/details/102235908
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.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
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.
