Master SpringBoot Annotations: A Complete Guide to @Controller, @Service, @Repository and More

This article provides a comprehensive overview of SpringBoot’s most commonly used annotations, covering MVC, bean, JPA, configuration, exception handling, and testing annotations, complete with clear explanations and practical code examples to help developers avoid pitfalls and write cleaner code.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master SpringBoot Annotations: A Complete Guide to @Controller, @Service, @Repository and More

Background Introduction

SpringBoot projects are countless, and unlike traditional Spring projects it provides a large number of annotations for rapid development, making it almost ready‑to‑use out of the box.

How many annotations does SpringBoot offer and how should they be used? This article organizes the most common ones, explains their meanings and usage, and helps you avoid common pitfalls.

Annotation Summary

2.1 SpringMVC Related Annotations

@Controller

– Marks a class as a controller that forwards user requests to service interfaces, usually used together with @RequestMapping. @RequestMapping – Provides routing information, mapping URLs to specific controller methods and can specify HTTP methods such as GET, POST, PUT, DELETE. @RequestBody – Indicates that the request body must be application/json and automatically binds the JSON data to a Java object. @ResponseBody – Writes the method’s return value directly to the HTTP response body, typically as application/json. @RestController – Combines @Controller and @ResponseBody, so all exposed methods return JSON by default. @RequestParam – Binds form‑type request parameters to method arguments. @PathVariable – Retrieves variables from a REST‑style URL path. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping – Shortcut annotations for @RequestMapping with a fixed HTTP method.

/**
 * Login service
 */
@Controller
@RequestMapping("api")
public class LoginController {

    /**
     * Login request, POST, JSON body
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity login(@RequestBody UserLoginDTO request) {
        //...business logic
        return new ResponseEntity(HttpStatus.OK);
    }
}
@RestController
@RequestMapping("api")
public class LoginController {

    /**
     * Login request, POST, JSON body
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity login(@RequestBody UserLoginDTO request) {
        //...business logic
        return new ResponseEntity(HttpStatus.OK);
    }
}

2.2 Bean Related Annotations

@Service

– Marks a service‑layer component and registers it as a Spring bean. @Component – Generic component annotation used when a more specific stereotype does not apply. @Repository – Marks a DAO component; Spring creates a proxy for exception translation. @Bean – Declares a bean method inside a @Configuration class, equivalent to an XML <bean> definition. @Autowired – Injects a bean by type (default) and can be optional with required = false. @Resource – JDK‑provided injection by name (default) or by type. @Qualifier – Disambiguates which bean to inject when multiple candidates exist. @Scope – Defines bean scope: singleton, prototype, request, session, etc.

@Service
public class DeptService {
    // business methods
}
@Component
public class DeptComponent {
    // business methods
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    // query methods
}
@Configuration
public class AppConfig {
    @Bean
    public Uploader initFileUploader() {
        return new FileUploader();
    }
}
@Autowired
private DeptService deptService;
@Resource(name = "deptService")
private DeptService deptService;
@Autowired
@Qualifier("deptService")
private DeptService deptService;
@RestController
@Scope("singleton")
public class HelloController {
}

2.3 JPA Related Annotations

@Entity

and @Table – Mark a class as a JPA entity and optionally specify the table name. @Id – Declares the primary‑key field. @Column – Maps a field to a table column; can be omitted if names match. @GeneratedValue – Defines primary‑key generation strategy (AUTO, IDENTITY, SEQUENCE, TABLE). @SequenceGenerator – Configures a database sequence used with @GeneratedValue. @Transient – Excludes a field from persistence. @Basic(fetch = FetchType.LAZY) – Enables lazy loading for a field. @JoinColumn – Specifies the foreign‑key column for relationships. @OneToOne, @OneToMany, @ManyToOne – Define entity relationships.

@Entity
@Table(name = "TB_ROLE")
@SequenceGenerator(name = "id_seq", sequenceName = "seq_repair", allocationSize = 1)
public class Role implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq")
    private Long id;

    @Column(nullable = false)
    private String roleName;

    @Column(nullable = false)
    private String roleType;
}
@Entity
@Table(name = "tb_login_log")
public class LoginLog implements Serializable {
    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
    // getters & setters
}

2.4 Configuration Related Annotations

@Configuration

– Declares a Java‑based configuration class. @EnableAutoConfiguration – Enables SpringBoot’s auto‑configuration mechanism. @ComponentScan – Specifies packages to scan for components. @SpringBootApplication – Combines @Configuration, @EnableAutoConfiguration and @ComponentScan; typically placed on the main class. @EnableTransactionManagement – Activates annotation‑driven transaction management. @Conditional family (e.g., @ConditionalOnBean, @ConditionalOnMissingBean, @ConditionalOnClass, @ConditionalOnProperty) – Conditional bean registration based on environment, classpath, or property values. @Value – Injects a property value from application.properties or other sources. @ConfigurationProperties – Binds a group of properties to a POJO. @PropertySource – Loads additional property files. @ImportResource – Imports XML configuration files.

@Configuration
public class AppConfig {
    @Bean
    public Uploader initOSSUploader() {
        return new OSSUploader();
    }
}

2.5 Exception Handling Annotations

@ControllerAdvice

– Global exception handling component. @ExceptionHandler – Handles specific exception types within @ControllerAdvice or a controller.

@ControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionConfig {
    private static final Integer GLOBAL_ERROR_CODE = 500;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        log.error("【统一异常处理器】", e);
        ResultMsg<Object> resultMsg = new ResultMsg<>();
        resultMsg.setCode(GLOBAL_ERROR_CODE);
        if (e instanceof CommonException) {
            CommonException ex = (CommonException) e;
            if (ex.getErrCode() != 0) {
                resultMsg.setCode(ex.getErrCode());
            }
            resultMsg.setMsg(ex.getErrMsg());
        } else {
            resultMsg.setMsg(CommonErrorMsg.SYSTEM_ERROR.getMessage());
        }
        WebUtil.buildPrintWriter(response, resultMsg);
    }
}

2.6 Testing Related Annotations

@ActiveProfiles

– Activates specific Spring profiles for tests. @RunWith and @SpringBootTest – Set up the Spring test context.

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestJunit {
    @Test
    public void executeTask() {
        // test logic
    }
}

Conclusion

The article is extensive; you can bookmark it and refer back when you need a quick reminder of SpringBoot annotations.

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.

javabackend-developmentannotationsSpringBootSpring MVC
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

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.