Explore 160 Real-World Spring Boot 3 Cases – Free PDF Updated to 130+
This article presents a free, continuously updated collection of 160 practical Spring Boot 3 examples, organized into nine annotation categories with clear explanations and code snippets, allowing developers to master component scanning, bean lifecycle, dependency injection, MVC, configuration, JPA, exception handling, AOP, and testing.
Efficient development is a goal for every developer; Spring Boot, with its powerful features and convenience, has become the framework of choice. Its rich set of annotations simplifies code and configuration, making project setup fast and painless.
This article systematically organizes nine categories covering 50 commonly used Spring Boot annotations, providing concise explanations and practical code examples for each.
1. Component‑related Annotations
@Controller marks a class as an MVC controller and works with @RequestMapping to route requests.
@Controller
@RequestMapping("/users")
public class UserController {
// ...
}@Service designates a service‑layer component.
@Service
public class UserService {
// ...
}@Repository marks a data‑access component; it is optional when using Spring Data JPA.
@Repository
public interface UserRepository extends JpaRepository<Role, Long> {
}@Component is a generic stereotype for beans that do not fit other categories.
@Component
public class MessageHandler {
}2. Bean Creation and Lifecycle Annotations
@Bean declares a method that produces a bean managed by the container.
@Configuration
public class AppConfig {
@Bean
public MessageHandler messageHandler() {
return new MessageHandler();
}
}@Scope defines the bean’s scope (singleton, prototype, request, session, application).
@Configuration
public class RestTemplateConfig {
@Bean
@Scope("prototype")
public RestTemplate restTemplate() {
return new RestTemplate();
}
}@Primary gives a bean priority when multiple candidates exist.
@Configuration
public class JavaConfig {
@Bean("b1")
@Primary
public B b1() { return new B(); }
@Bean("b2")
public B b2() { return new B(); }
}@PostConstruct runs after dependency injection for initialization.
public class UserService {
@PostConstruct
public void init() {
// initialization logic
}
}@PreDestroy runs before the bean is removed from the container.
@Service
public class UserService {
@PreDestroy
public void cleanUp() {
// cleanup logic
}
}3. Dependency‑Injection Annotations
@Autowired injects a bean by type, optionally with required = false.
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@Autowired(required = false)
private CommonService commonService;
}@Resource injects by name (or by type with type = …).
@RestController
@RequestMapping("/users")
public class UserController {
@Resource(name = "userServiceImpl")
private UserService userService;
}@Qualifier selects a specific bean when multiple candidates exist.
@Autowired
@Qualifier("userService")
private UserService userService;4. Spring MVC Annotations
@RequestMapping maps URLs to controller methods and can specify HTTP methods.
@RequestBody binds JSON request bodies to Java objects.
@ResponseBody writes the method’s return value directly to the HTTP response.
@Controller
@RequestMapping("/api")
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> login(@RequestBody UserLoginDTO request) {
return ResponseEntity.ok("success");
}
}@RestController combines @Controller and @ResponseBody.
@RequestParam extracts query/form parameters.
@RequestMapping(value = "login", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestParam("username") String username,
@RequestParam("pwd") String password) {
// ...
}@PathVariable captures variables from the URL path.
@RequestMapping(value = "/products/{id}", method = RequestMethod.POST)
public ResponseEntity<?> queryProduct(@PathVariable("id") Long id) {
// ...
}Shortcut annotations such as @GetMapping , @PostMapping , @PutMapping , and @DeleteMapping are equivalents of @RequestMapping with a fixed HTTP method.
@GetMapping("/get")
public ResponseEntity<?> get() { /* ... */ }
@PostMapping("/post")
public ResponseEntity<?> post() { /* ... */ }5. Configuration‑Class Annotations
@Configuration declares a Java‑based configuration class.
@Configuration
public class AppConfig {
@Bean
public CommonUtils commonUtils() {
return new CommonUtils();
}
}@EnableAutoConfiguration enables Spring Boot’s auto‑configuration mechanism.
@Configuration
@EnableAutoConfiguration
public class PackAutoConfiguration { }@ComponentScan specifies packages to scan for components.
@Configuration
@ComponentScan(basePackages = {"com.pack", "com.xg"})
public class AppConfig { }@SpringBootApplication is a shortcut for @Configuration, @EnableAutoConfiguration, and @ComponentScan.
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}@EnableTransactionManagement activates annotation‑driven transaction management.
@SpringBootApplication
@EnableTransactionManagement
public class App { }@ConfigurationProperties binds external configuration properties to a POJO.
# application.yml
pack:
app:
title: xxxooo
version: 1.0.0
@Component
@ConfigurationProperties(prefix = "pack.app")
public class AppProperties {
private String title;
private String version;
// getters and setters
}@Conditional and its variants ( @ConditionalOnBean, @ConditionalOnMissingBean, @ConditionalOnClass, @ConditionalOnMissingClass, @ConditionalOnExpression, @ConditionalOnProperty) allow beans to be loaded only when specific conditions are met.
@Configuration
public class ConditionalConfig {
/** Create A when Test bean exists */
@ConditionalOnBean(Test.class)
@Bean
public A createA() { return new A(); }
/** Create B when Test bean is missing */
@ConditionalOnMissingBean(Test.class)
@Bean
public B createB() { return new B(); }
}6. JPA‑Related Annotations
@Entity and @Table map a class to a database table.
@Id , @GeneratedValue , and @Column define primary keys and column mappings.
@Entity
@Table(name = "TB_ROLE")
@SequenceGenerator(name = "id_seq", sequenceName = "seq_repair", allocationSize = 1)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq")
private Long id;
@Column(nullable = false)
private String roleName;
@Column(nullable = false)
private String roleType;
}@Transient excludes a field from persistence.
@Column(nullable = false)
@Transient
private String lastTime;@OneToOne , @OneToMany , @ManyToOne and @JoinColumn define relationships between entities.
@Entity
public class User {
@OneToOne
@JoinColumn(name = "user_id")
private IdCard card;
}
@Entity
public class Customer {
@Id
private Long id;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Address> addresses = new ArrayList<>();
}
@Entity
public class Address {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "c_id", nullable = false)
private Customer customer;
}7. Exception‑Handling Annotations
@ControllerAdvice combined with @ExceptionHandler provides global exception handling.
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Integer GLOBAL_ERROR_CODE = 500;
@ExceptionHandler(Exception.class)
public void handle(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
// build and write error response
}
}8. AOP Annotations
@Aspect defines a cross‑cutting concern; @Before , @After , @AfterReturning , @AfterThrowing , @Around , and @Pointcut specify advice types and join points. @Order sets execution precedence.
@Aspect
@Component
@Order(1)
public class WebLogAspect {
@Pointcut("execution(public * com.example.web.controller.*.*(..))")
public void webLog() {}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) { /* ... */ }
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = joinPoint.proceed();
return result;
}
}9. Testing Annotations
@Test marks a method as a unit test; @RunWith and @SpringBootTest bootstrap the Spring context; @ActiveProfiles selects configuration profiles.
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestJunit {
@Test
public void testTask() {
// test logic
}
}The article concludes with a reminder to like, share, and collect the resource, and provides links to related Spring Boot tutorials.
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.
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.
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.
