Overview of Common Spring and JPA Annotations

This article provides a comprehensive overview of frequently used Spring Boot, Spring MVC, and JPA annotations, explaining their purposes, typical usage patterns, and includes example code snippets to illustrate how they are applied in Java backend development.

Java Captain
Java Captain
Java Captain
Overview of Common Spring and JPA Annotations

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 an XML configuration file; using Java code provides type safety.

@EnableAutoConfiguration: Enables automatic configuration.

@ComponentScan: Scans for components and automatically registers beans.

@Component: Can be used with CommandLineRunner to execute tasks after application startup.

@RestController: A combination of @Controller and @ResponseBody; the controller’s return value is written directly to the HTTP response body.

@Autowired: Automatic dependency injection.

@PathVariable: Retrieves path parameters.

@JsonBackReference: Solves circular reference problems during JSON serialization.

@RepositoryRestResource: Used together with spring-boot-starter-data-rest.

2. Detailed Annotation Explanations

@SpringBootApplication: Declares that Spring Boot should automatically configure the application, equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan.

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 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<String,Object> map) {
        System.out.println("DemoController.hello()");
        map.put("hello","from DemoController.helloHtml");
        // will render hello.html or hello.ftl
        return "/hello";
    }
}

@RestController: Combines @Controller and @ResponseBody for REST‑style controllers.

@RestController
@RequestMapping("/demoInfo2")
public class DemoController2 {
    @RequestMapping("/test")
    public String test() {
        return "ok";
    }
}

@RequestMapping: Provides routing information, mapping URLs to controller methods.

@EnableAutoConfiguration: Enables Spring Boot’s auto‑configuration based on classpath dependencies.

@ComponentScan: Scans the package of the annotated class (and sub‑packages) for beans annotated with @Component, @Service, @Repository, etc.

@Configuration: Serves as a Java‑based replacement for XML configuration files; can import XML with @ImportResource.

@Import: Imports additional configuration classes.

@ImportResource: Loads XML configuration files.

@Autowired: Automatic injection of dependent beans.

@Service: Marks a class as a service layer component.

@Repository: Marks a DAO/repository; enables exception translation and component scanning.

@Bean: Declares a bean produced by a method, similar to an XML <bean> definition.

@Value: Injects property values from application.properties or other property sources.

@Value("#{message}")
private String message;

@Inject: Equivalent to @Autowired but without the required attribute.

@Qualifier: Disambiguates injection when multiple beans of the same type exist.

@Autowired
@Qualifier("demoInfoService")
private DemoInfoService demoInfoService;

@Resource(name="name", type="type"): Similar to @Autowired; defaults to byName injection when no attributes are specified.

3. JPA Annotations

@Entity, @Table(name=""): Marks a class as a JPA entity; @Table can be omitted if the table name matches the class name.

@MappedSuperclass: Indicates that a class’s mapping information is inherited by subclasses.

@NoRepositoryBean: Prevents Spring Data from creating an instance of the annotated repository interface.

@Column: Maps a field to a database column; can be omitted when names match.

@Id: Declares the primary‑key field.

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "repair_seq"): Configures primary‑key generation using a database sequence.

@SequenceGenerator(name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1): Defines a sequence generator.

@Transient: Excludes a field from persistence.

@JsonIgnore: Excludes a property from JSON serialization/deserialization.

@JoinColumn(name="loginId"): Specifies a foreign‑key column for relationships.

@OneToOne, @OneToMany, @ManyToOne: Defines entity relationships.

4. Spring MVC Related Annotations

@RequestMapping: Maps HTTP requests to handler methods; attributes include params, headers, value, method, consumes, and produces.

@RequestParam: Binds a request parameter to a method argument.

@PathVariable: Binds a URI template variable to a method argument.

@RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress) {
    // do something;
}

5. Global Exception Handling

@ControllerAdvice: A specialization of @Component that allows centralized exception handling across all controllers.

@ExceptionHandler(Exception.class): Declares a method to handle the specified exception type.

(End of article)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaspringannotationsSpringBootjpa
Java Captain
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.