Mastering Spring Boot Annotations: A Complete Guide
This article provides a comprehensive overview of Spring Boot, Spring MVC, and JPA annotations, explaining their purposes, usage, and interactions, and includes practical code examples for each annotation to help developers quickly apply them in real projects.
1. Annotation List
@SpringBootApplication : Combines @ComponentScan, @Configuration and @EnableAutoConfiguration.
@Configuration : Equivalent to an XML configuration file; enables type‑safe Java‑based configuration.
@EnableAutoConfiguration : Triggers Spring Boot’s auto‑configuration mechanism.
@ComponentScan : Scans for components such as @Component, @Service, @Repository, etc.
@Component : Generic stereotype for any Spring‑managed component.
@RestController : Combination of @Controller and @ResponseBody for REST‑style controllers.
@Autowired : Automatic dependency injection.
@PathVariable : Binds method parameters to URI template variables.
@JsonBackReference : Handles circular references during JSON serialization.
@RepositoryRestResource : Used with spring‑boot‑starter‑data‑rest.
2. Annotation Details
@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 return value should be written directly to the HTTP response body, commonly used for RESTful APIs.
@RequestMapping("/test")
@ResponseBody
public String test(){
return "ok";
}@Controller marks a class as a Spring MVC controller; methods are typically mapped with @RequestMapping.
@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 render hello.html or hello.ftl
return "/hello";
}
}@RestController is a shortcut for @Controller + @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 controller methods.
@EnableAutoConfiguration lets Spring Boot attempt to configure the application based on the jars present on the classpath.
@ComponentScan automatically discovers beans annotated with @Component, @Service, @Repository, etc., within the package of the annotated class and its sub‑packages.
@Configuration serves as a Java‑based replacement for XML configuration files; can import additional resources with @Import or @ImportResource.
@Import imports other configuration classes.
@ImportResource loads XML configuration files.
@Service marks a service‑layer component.
@Repository marks a DAO component and enables exception translation.
@Bean declares a bean method, equivalent to an XML <bean> definition.
@Value injects property values from application.properties.
@Value(value = "#{message}")
private String message;@Inject is functionally equivalent to @Autowired but without the required attribute.
@Qualifier disambiguates injection when multiple beans of the same type exist.
@Autowired
@Qualifier(value = "demoInfoService")
private DemoInfoService demoInfoService;@Resource (name="name", type="type") performs injection by name by default, similar to @Autowired.
3. JPA Annotations
@Entity marks a class as a JPA entity; often used together with @Table.
@MappedSuperclass designates a superclass whose mapping information is applied to its subclasses.
@NoRepositoryBean indicates that Spring Data should not create an implementation for the annotated repository interface.
@Column maps a field to a database column; can be omitted if names match.
@Id denotes the primary key field.
@GeneratedValue defines the primary‑key generation strategy, e.g., SEQUENCE.
@SequenceGenerator configures a database sequence.
@Transient excludes a field from persistence.
@JsonIgnore prevents a property from being serialized to JSON.
@JoinColumn specifies a foreign‑key column for relationships.
@OneToOne, @OneToMany, @ManyToOne define entity relationships.
4. Spring MVC Annotations
@RequestMapping maps URLs to controller classes or methods and supports attributes such as params, headers, value, method, consumes, and produces.
@RequestParam binds request parameters to method arguments.
@PathVariable binds URI template variables to method arguments.
RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
// do something
}5. Global Exception Handling
@ControllerAdvice combines @Component and allows centralized exception handling across all controllers.
@ExceptionHandler marks a method to handle specific exception types.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack 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.
