Common Spring Boot Annotations and Their Usage
This article provides a comprehensive overview of common Spring Boot annotations—including core annotations, MVC‑related annotations, JPA mapping annotations, and global exception handling—along with example Java code illustrating their practical usage in backend development.
Spring Boot provides several core annotations such as @SpringBootApplication , @Configuration , @EnableAutoConfiguration , and @ComponentScan , which together configure component scanning, auto‑configuration, and bean registration.
Other frequently used annotations include @RestController , @Controller , @ResponseBody , @RequestMapping , @PathVariable , @Autowired , @Qualifier , @Value , and @Resource , each serving specific purposes in request handling, dependency injection, and configuration.
For JPA, annotations like @Entity , @Table , @Id , @GeneratedValue , @OneToOne , @OneToMany , @ManyToOne , @JoinColumn , and @Transient define entity mapping and relationships.
Global exception handling can be centralized with @ControllerAdvice and @ExceptionHandler .
Example code snippets illustrate the usage of these annotations in typical Spring Boot applications:
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);
}
} @RequestMapping("/test")
@ResponseBody
public String test(){
return "ok";
} @Controller
@RequestMapping("/demoInfo")
public class DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map
map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
// will use hello.html or hello.ftl template for rendering
return "/hello";
}
} 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";
}
} @Value(value = "#{message}")
private String message; @Autowired
@Qualifier(value = "demoInfoService")
private DemoInfoService demoInfoService; RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
// do something;
}Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.