Mastering Spring Boot Annotations: A Comprehensive Guide for Backend Developers

This article provides a thorough overview of Spring Boot's core, web, configuration, dependency injection, AOP, testing, security, transaction, scheduling, event, exception handling, property binding, and conditional annotations, complete with practical code examples for Java backend development.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Spring Boot Annotations: A Comprehensive Guide for Backend Developers

1. Core Annotations

@SpringBootApplication combines @Configuration, @EnableAutoConfiguration and @ComponentScan. Example:

@SpringBootApplication
public class SpringbootPackApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDbApplication.class, args);
    }
}

@Component registers a class as a Spring bean.

@Component
public class PackComponent {
}

Specialized stereotypes @Service , @Repository , @Controller are meta‑annotated with @Component for service, DAO and MVC layers respectively.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

@Service
public class UserService {}

@Controller
public class UserController {}

2. Web Layer Annotations

@RestController is a shortcut for @Controller + @ResponseBody, causing method return values to be written directly to the response body.

@RestController
public class UserController {
    @RequestMapping("/index")
    public R index() {
        return R.success();
    }
}

Mapping annotations such as @RequestMapping, @GetMapping, @PostMapping define the HTTP method handling.

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("")
    public R query() { return R.success(); }

    @PostMapping("")
    public R save(User user) { return R.success(user); }
}

3. Bean Configuration

@Configuration marks a class as a source of bean definitions.

@Configuration
public class AppConfig {
    @Bean
    public PackComponent packComponent() {
        return new PackComponent();
    }
}

@Bean declares that a method produces a bean managed by the IoC container.

@Configuration
public class AppConfig {
    @Bean
    public UserBean userBean() {
        return new UserBean();
    }
}

4. Dependency‑Injection Annotations

@Autowired injects a bean by type; it can be placed on fields, constructors, methods, or parameters.

@Autowired
private UserRepository userRepository;

@Autowired
public UserService(CommonComponent cc) { }

@Qualifier works with @Autowired to specify which bean should be injected when multiple candidates exist.

@Service
public class UserService {
    private final DAO dao;

    @Autowired
    public UserService(@Qualifier("userDAO") DAO dao) {
        this.dao = dao;
    }
}

5. AOP Annotations

@Aspect declares a class as an aspect. Inside an aspect you can define advice methods with @Before, @After, @AfterReturning, @AfterThrowing and pointcuts with @Pointcut.

@Component
@Aspect
public class LoggerAspect {
    @Before("bean(*Service) && args(id,name)")
    public void beforeLogAndArgs(JoinPoint jp, Long id, String name) {
        System.out.printf("id = %d, name = %s%n", id, name);
    }

    @After("recordLog()")
    public void after(JoinPoint jp) {
        System.out.println("最终通知");
    }

    @AfterReturning(value = "recordLog()", returning = "ret")
    public void afterReturningLog(JoinPoint.StaticPart jp, Object ret) {
        System.out.printf("接受到返回值: %s%n", ret);
    }

    @AfterThrowing(value = "recordLog()", throwing = "ex")
    public void afterThrowingLog(JoinPoint jp, Throwable ex) {
        System.err.printf("发生异常: %s%n", ex.getMessage());
    }
}

Pointcut definitions:

@Aspect
public class LoggerAspect {
    @Pointcut("execution(public * com.pack.PersonService.query*(..))")
    private void recordLog() {}

    @Pointcut(value = "args(id)", argNames = "id")
    private void argsPointcut(Long id) {}
}

6. Testing Annotations

@SpringBootTest loads the full application context for integration tests.

@SpringBootTest
public class PackApplicationTests {
    // @Test methods
}

Specialized test slices such as @DataJpaTest and @WebMvcTest limit the context to JPA or MVC components.

@WebMvcTest(UserController.class)
public class UserControllerTest {
    // MVC test cases
}

7. Security Annotations

@EnableGlobalMethodSecurity enables method‑level security (pre/post, secured, JSR‑250) on a @Configuration class.

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration { }

Method‑level checks use @PreAuthorize, @PostAuthorize, @Secured, etc.

@Service
public class UserService {
    @PreAuthorize("hasRole('ROLE_USER')")
    public void query() { }
}

8. Transaction Management

@EnableTransactionManagement activates annotation‑driven transaction management.

@Configuration
@EnableTransactionManagement
public class TransactionConfig { }

@Transactional can be placed on classes or methods to run them within a transaction.

@Service
@Transactional
public class UserService {
    public void save(User user) { }

    @Transactional
    public void update() { }
}

9. Scheduling

@EnableScheduling enables support for @Scheduled methods.

@Configuration
@EnableScheduling
public class SchedulingConfig { }

@Scheduled marks a method to be executed periodically.

@Component
public class ScheduledTasks {
    @Scheduled(fixedRate = 1000)
    public void task01() { }
}

10. Event Listener Annotations

@EventListener registers a method to handle application events.

@Component
public class CustomEventListener {
    @EventListener(UserEvent.class)
    public void userEvent() { }
}

@TransactionalEventListener can be used to handle events after transaction commit.

11. Exception‑Handling Annotations

@ControllerAdvice defines a global component for handling exceptions across controllers.

@ControllerAdvice
public class GlobalControllerAdvice { }

@ExceptionHandler inside a @ControllerAdvice or @Controller processes specific exceptions.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleCustomException(Exception ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }
}

@ResponseStatus can be placed on an exception class or method to set the HTTP status.

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
public class ResourceNotFoundException extends RuntimeException { }

12. Property Binding

@Value injects a single property value.

@Value("${pack.title}")
private String title;

@ConfigurationProperties binds a group of properties to a POJO.

@ConfigurationProperties(prefix = "pack.point")
public class Point {
    private Double x;
    private Double y;
    // getters, setters
}

@PropertySources (or @PropertySource) loads external .properties files.

@PropertySources({@PropertySource("classpath:pack.properties")})
public class PropertyConfig { }

13. Conditional Annotations

Spring provides many @Conditional‑based annotations to control bean creation. Custom conditions can be defined by implementing Condition.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Conditional(PackConditionProperty.class)
public @interface PackCondition { }

public class PackConditionProperty implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Boolean result = context.getEnvironment().getProperty("pack.config.enabled", Boolean.class, true);
        return result;
    }
}
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.

testingBackend DevelopmentSpring Bootannotationsdependency-injection
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

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.