IT Company Rajkot

Impex Infotech is a global Web Development Company providing IT solutions to companies worldwide.

Impex Infotech Office No. 314, Pride Universe, University Rd, opposite Gujarat Water Supply and Sewerage Board, Rajkot, Gujarat 360005

Open in Google Maps

Spring Boot Annotations: The Complete 2026 Guide With Examples (and How AI Helps You Use Them Correctly)

⏱ 24 min read · Updated for Spring Boot 4.1, October 2026
Best Inventory Management Software Solutions for Small Business in 2026: Pricing, Features and When to Go Custom (USA & India)
⚡ Quick Answer

Spring Boot annotations are Java metadata that tell Spring how to build and wire your application: @SpringBootApplication starts it, stereotypes such as @Service and @RestController register beans, @GetMapping and @RequestBody map HTTP requests, @ConfigurationProperties binds settings, @Transactional wraps database work, and test annotations such as @WebMvcTest and @MockitoBean load just enough of the app to test it. The current line is Spring Boot 4.1 (4.1.2 on spring.io in October 2026), which needs Java 17 or later, runs on Spring Framework 7 and uses the jakarta.* namespace. AI assistants can explain, generate and migrate annotated code quickly, but you still need to check imports, versions and proxy behaviour yourself.

🎯 Key Takeaways

  • @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan.
  • Prefer constructor injection; @Autowired is optional when a class has a single constructor.
  • @Transactional, @Async, @Cacheable and @PreAuthorize work through proxies, so calls from inside the same class bypass them.
  • By default @Transactional rolls back only on unchecked exceptions and errors; checked exceptions need rollbackFor.
  • @MockBean was deprecated in Spring Boot 3.4; use @MockitoBean and @MockitoSpyBean from Spring Framework.
  • Treat AI-generated Spring code as a draft and check imports, versions and transaction boundaries.

01Spring Boot in 2026: Versions, Java and Jakarta EE

The spring.io project page lists Spring Boot 4.1.2 as the current release. Spring Boot 4.1.0 was announced on 10 June 2026; the 4.x line began in November 2025 with Spring Framework 7.0. According to the Spring Boot 4.1 system requirements page, it needs Java 17 or later (compatible up to Java 27), Spring Framework 7.0.10 or above, Maven 3.6.3 or later or Gradle 8.14+ / 9.x, and a Servlet 6.1 container such as Tomcat 11 or Jetty 12.1.

The Spring Boot 4.0 release notes list Jakarta Servlet 6.1, Persistence 3.2 and Validation 3.1, part of the Jakarta EE 11 baseline, so persistence and validation annotations come from jakarta.*, never javax.*. Spring Framework 7 also drops support for the old javax.annotation and javax.inject annotations, so @PostConstruct and @Inject must come from their jakarta packages.

On Spring Boot 3.x, nearly everything here still applies. The differences we flag are mainly test annotation packages, Jackson 3, and annotations deprecated in 3.x.

ℹ️ How this guide was checked

Versions, defaults and deprecations were checked against docs.spring.io, spring.io and the Spring Boot release notes on 28 October 2026. Code examples use a hypothetical order-management API and were reviewed against the official documentation, not compiled in a live project.

02How Spring Boot Annotations Actually Work

An annotation on its own does nothing. It is a label that some part of Spring reads at startup or at runtime, and knowing which part explains most surprising behaviour.

There are three broad mechanisms. First, component scanning: at startup Spring walks your packages, finds classes marked with @Component or one of its specialisations, and registers them as beans. Second, auto-configuration: Spring Boot ships hundreds of configuration classes guarded by conditions such as @ConditionalOnClass, and only activates the ones whose conditions match your classpath and properties. Third, proxies: for transactions, caching, async execution and method security, Spring wraps your bean in a proxy that runs extra logic around each call coming through it.

The third mechanism is the one that bites. The Spring Framework reference states that self-invocation, a method calling another method on this, bypasses the proxy, and that private and final methods cannot be advised by class-based proxies. If design patterns are your mental model, this is the Proxy pattern from our guide to software design patterns, applied at framework scale.

03The Spring Boot Annotations List (Master Table)

The annotations most teams use in production, grouped like the examples that follow. Packages are for Spring Boot 4.1 and Spring Framework 7.

Spring Boot annotations list: package, purpose and where to use each (Spring Boot 4.1, October 2026)
AnnotationPackage / moduleWhat it doesWhere you use it
Core and bootstrapping
@SpringBootApplicationorg.springframework.boot.autoconfigureCombines configuration, auto-configuration and component scanningMain class in the root package
@SpringBootConfigurationorg.springframework.bootBoot’s variant of @Configuration, helps tests find configurationUsually implicit via @SpringBootApplication
@EnableAutoConfigurationorg.springframework.boot.autoconfigureActivates conditional auto-configurationUsually implicit
@ComponentScanorg.springframework.context.annotationFinds @Component classes in a package treeUsually implicit; explicit for unusual layouts
@Configurationorg.springframework.context.annotationMarks a class that declares beansConfig classes
@Beanorg.springframework.context.annotationRegisters a method’s return value as a beanMethods in config classes
@Importorg.springframework.context.annotationPulls in other configuration classesConfig classes, tests
@AutoConfigurationorg.springframework.boot.autoconfigureMarks a class as auto-configurationLibraries and internal starters
Stereotypes and dependency injection
@Componentorg.springframework.stereotypeGeneric Spring-managed beanHelpers, adapters
@Serviceorg.springframework.stereotypeComponent holding business logicService layer
@Repositoryorg.springframework.stereotypeData-access component with exception translationHand-written DAOs (not Spring Data interfaces)
@Controllerorg.springframework.stereotypeMVC controller returning viewsServer-rendered pages
@Autowiredorg.springframework.beans.factory.annotationRequests injectionOptional on a single constructor; tests
@Qualifierorg.springframework.beans.factory.annotationChooses one bean among several of a typeConstructor parameters
@Primaryorg.springframework.context.annotationDefault bean when several matchBean definitions
@Lazyorg.springframework.context.annotationDelays bean creation until first useExpensive or rarely used beans
Web
@RestControllerorg.springframework.web.bind.annotation@Controller + @ResponseBody; returns data, not viewsJSON APIs
@RequestMappingorg.springframework.web.bind.annotationMaps a URL prefix or requestClass level for a base path
@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMappingorg.springframework.web.bind.annotationHTTP-method-specific mappingsHandler methods
@PathVariableorg.springframework.web.bind.annotationBinds a URI template segment/orders/{id}
@RequestParamorg.springframework.web.bind.annotationBinds a query or form parameterFilters, paging
@RequestBodyorg.springframework.web.bind.annotationDeserialises the request bodyPOST/PUT payloads
@ResponseStatusorg.springframework.web.bind.annotationSets the response status codeHandlers, exception classes
@RestControllerAdvice / @ControllerAdviceorg.springframework.web.bind.annotationCross-controller exception handling and bindingGlobal error handler class
@ExceptionHandlerorg.springframework.web.bind.annotationMaps an exception type to a responseMethods in advice classes
Configuration
@Valueorg.springframework.beans.factory.annotationInjects one property or SpEL expressionSingle, simple values
@ConfigurationPropertiesorg.springframework.boot.context.propertiesBinds a property prefix to a typed objectGrouped settings
@EnableConfigurationProperties / @ConfigurationPropertiesScanorg.springframework.boot.context.propertiesRegisters properties classes explicitly or by scanningConfig or main class
@Profileorg.springframework.context.annotationActivates a bean only for named profilesEnvironment-specific beans
Conditionals
@ConditionalOnPropertyorg.springframework.boot.autoconfigure.conditionMatches on a property valueFeature flags in config
@ConditionalOnClassorg.springframework.boot.autoconfigure.conditionMatches when a class is on the classpathAuto-configuration
@ConditionalOnMissingBeanorg.springframework.boot.autoconfigure.conditionBacks off if the user defined a beanAuto-configuration only
Data, JPA and transactions
@Entity, @Table, @Columnjakarta.persistenceMap a class and fields to a tableDomain entities
@Id, @GeneratedValuejakarta.persistencePrimary key and generation strategyEntity ID field
@Transactionalorg.springframework.transaction.annotationRuns a method in a transactionPublic service methods
Validation
@Validjakarta.validationCascades Bean Validation to an object@RequestBody parameters, nested fields
@Validatedorg.springframework.validation.annotationSpring’s variant; supports groups and AOP method validation@ConfigurationProperties, service classes
@NotNull, @NotBlank, @Size, @Emailjakarta.validation.constraintsField and parameter constraintsDTOs, properties classes
Scheduling, async, caching and security
@EnableScheduling / @Scheduledorg.springframework.scheduling.annotationRuns methods on a cron or fixed scheduleBackground jobs
@EnableAsync / @Asyncorg.springframework.scheduling.annotationRuns a method on another threadFire-and-forget work
@EnableCaching, @Cacheable, @CacheEvictorg.springframework.cache.annotationCaches return values and clears entriesRead-heavy lookups
@EnableMethodSecurity, @PreAuthorizeorg.springframework.security.config.annotation.method.configuration / org.springframework.security.access.prepostMethod-level authorisationService methods
Testing
@SpringBootTestorg.springframework.boot.test.contextStarts the full application contextIntegration tests
@WebMvcTestorg.springframework.boot.webmvc.test.autoconfigure (Boot 4)Loads only the MVC layer with MockMvcController tests
@DataJpaTestorg.springframework.boot.data.jpa.test.autoconfigure (Boot 4)Loads only JPA componentsRepository tests
@MockitoBean / @MockitoSpyBeanorg.springframework.test.context.bean.override.mockitoReplaces or spies on a bean in the test contextSlice and integration tests
@TestConfigurationorg.springframework.boot.test.contextAdds test-only beans without replacing main configTests

04Spring Boot Annotations With Examples

Each group gives a short explanation, a compact example and the trap worth knowing. Imports are shown where the package matters.

Core and bootstrapping: @SpringBootApplication explained

The official reference describes @SpringBootApplication as a single annotation that enables three features: @EnableAutoConfiguration for Spring Boot’s auto-configuration, @ComponentScan on the package where the application lives, and @SpringBootConfiguration for registering extra beans or importing configuration. Because scanning starts at the annotated class’s package, place the main class in your root package, such as com.example.orders, with feature packages beneath it.

package com.example.orders;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class OrdersApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrdersApplication.class, args);
    }
}

Use @Configuration with @Bean methods to create objects you do not own, such as a third-party client or a Clock. proxyBeanMethods = false skips subclass generation when bean methods do not call each other.

@Configuration(proxyBeanMethods = false)
public class TimeConfig {

    @Bean
    Clock clock() {
        return Clock.systemUTC();
    }
}

@Import pulls specific configuration classes into the context, which is mainly useful in tests. And you do not need to add @EnableAutoConfiguration next to @Configuration in a Boot app; it is already part of @SpringBootApplication.

Stereotypes and dependency injection

@Component is the generic stereotype; @Service, @Repository and @Controller are specialisations that signal intent and, in the case of @Repository, enable translation of persistence exceptions into Spring’s DataAccessException hierarchy. Spring Data repository interfaces do not need @Repository; extending JpaRepository is enough.

Constructor injection is the preferred style. It makes dependencies explicit and final, and keeps classes easy to unit test. With a single constructor, Spring uses it automatically, so @Autowired is unnecessary.

@Service
public class OrderService {

    private final OrderRepository orders;
    private final PaymentGateway payments;

    public OrderService(OrderRepository orders,
                        @Qualifier("stripeGateway") PaymentGateway payments) {
        this.orders = orders;
        this.payments = payments;
    }
}

When two beans implement the same interface, mark the default with @Primary and name exceptions at the injection point with @Qualifier. @Lazy delays creating a bean until first use; it can speed startup but hides configuration errors until runtime.

Web and REST controllers

@RestController combines @Controller and @ResponseBody, so return values are written to the response body as JSON rather than resolved as view names. Put @RequestMapping at class level for the base path and use the method-specific shortcuts on handlers; they are clearer than @RequestMapping(method = ...) and are what most codebases use today.

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public OrderDto get(@PathVariable Long id) {
        return service.find(id);
    }

    @GetMapping
    public List<OrderDto> list(@RequestParam(defaultValue = "0") int page) {
        return service.list(page);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public OrderDto create(@Valid @RequestBody CreateOrderRequest request) {
        return service.create(request);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }
}

@PathVariable reads a URL segment, @RequestParam a query parameter, and @RequestBody converts JSON into a Java object (with Jackson 3 in Spring Boot 4). @ResponseStatus sets the status code on success; return a ResponseEntity for dynamic statuses or headers. For a broader view of how these APIs fit into products, see our overview of web application development.

Error handling with @RestControllerAdvice, @ExceptionHandler and ProblemDetail

Scattering try/catch blocks across controllers leads to inconsistent error bodies. A single @RestControllerAdvice class with @ExceptionHandler methods centralises the mapping. Spring Framework supports RFC 9457 “Problem Details for HTTP APIs”, and you can return a ProblemDetail directly from an exception handler; Spring renders it as application/problem+json.

@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(OrderNotFoundException.class)
    public ProblemDetail handleNotFound(OrderNotFoundException ex) {
        ProblemDetail problem =
                ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Order not found");
        return problem;
    }
}

To render Spring MVC’s own exceptions in the same format, either extend ResponseEntityExceptionHandler in your advice class or set spring.mvc.problemdetails.enabled=true so Spring Boot registers one for you.

Configuration: @Value vs @ConfigurationProperties, and @Profile

@Value("${app.feature.enabled:false}") injects a single property with an optional default, and also evaluates SpEL. It is fine for one or two values. For a group of related settings, @ConfigurationProperties is better: it binds a whole prefix to a typed object, supports relaxed names such as base-url to baseUrl, converts durations and data sizes, and can be validated. The Spring Boot Javadoc notes that, unlike @Value, SpEL expressions are not evaluated in these classes.

app:
  payments:
    base-url: https://payments.example.com
    timeout: 5s
    retries: 3
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import java.time.Duration;

@Validated
@ConfigurationProperties(prefix = "app.payments")
public record PaymentProperties(
        @NotBlank String baseUrl,
        Duration timeout,
        @Min(0) int retries) {
}

A properties class must be registered: either list it in @EnableConfigurationProperties(PaymentProperties.class) on a configuration class, or add @ConfigurationPropertiesScan to the main class as shown earlier. Records bind through their constructor. @Profile("dev") on a bean or configuration class activates it only when that profile is active, which suits local stubs and seed data.

Conditional annotations

Conditionals decide what auto-configuration creates; you write them when building an internal starter. @ConditionalOnClass checks the classpath, @ConditionalOnProperty checks a property value, and @ConditionalOnMissingBean backs off when the application has already defined a bean of that type.

@AutoConfiguration
@ConditionalOnClass(name = "com.example.payments.StripeClient")
public class PaymentsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "app.payments", name = "provider", havingValue = "stripe")
    PaymentGateway stripeGateway(PaymentProperties properties) {
        return new StripeGateway(properties);
    }
}

The Spring Boot Javadoc for @ConditionalOnMissingBean says it can only match bean definitions processed so far and strongly recommends using it on auto-configuration classes only. Placed on an ordinary @Configuration class, it can produce results that depend on scanning order.

Data and JPA mapping

JPA annotations come from the Jakarta Persistence specification, not from Spring, which is why they live in jakarta.persistence. @Entity marks a persistent class, @Table and @Column customise names and constraints, @Id marks the primary key and @GeneratedValue chooses how it is produced.

import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "customer_email", nullable = false, length = 320)
    private String customerEmail;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    protected Order() {
        // required by JPA
    }
}

For relationships, @ManyToOne is eager by default under the JPA specification, so setting FetchType.LAZY explicitly is a common performance safeguard. @OneToMany(mappedBy = ...) marks the inverse side, and the owning side holds the foreign key through @JoinColumn. The repository needs no annotation:

public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByCustomerEmail(String customerEmail);
}

Transactions: @Transactional rollback rules, propagation and readOnly

@Transactional is the annotation most often misunderstood, and many tutorials still get its default wrong. The Spring Framework reference states that, by default, a transaction is marked for rollback only for unchecked exceptions (RuntimeException and subclasses) and Error. A checked exception thrown from a transactional method does not cause a rollback unless you configure it.

@Service
public class CheckoutService {

    private final OrderRepository orders;
    private final AuditService audit;

    public CheckoutService(OrderRepository orders, AuditService audit) {
        this.orders = orders;
        this.audit = audit;
    }

    @Transactional(rollbackFor = PaymentDeclinedException.class)
    public Receipt checkout(Cart cart) throws PaymentDeclinedException {
        Order order = orders.save(Order.from(cart));
        audit.record("checkout", order.getId()); // separate bean, so the proxy applies
        return chargeOrThrow(order);
    }

    @Transactional(readOnly = true)
    public List<OrderDto> history(String email) {
        return orders.findByCustomerEmail(email).stream().map(OrderDto::from).toList();
    }
}

@Service
class AuditService {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String action, Long orderId) {
        // committed even if the caller's transaction later rolls back
    }
}

The default propagation, REQUIRED, joins or starts a transaction; REQUIRES_NEW runs in a fresh one, which suits audit logs that must survive a rollback. readOnly = true is an optimisation hint for queries.

Two traps follow from the proxy model. First, self-invocation: if record lived in CheckoutService and was called as this.record(...), the REQUIRES_NEW setting would be silently ignored. Second, visibility: since Spring Framework 6.0, protected and package-visible methods can be transactional with class-based proxies, but private methods never can, and interface-based proxies require public methods. Since 6.2 you can also roll back on all exceptions globally with @EnableTransactionManagement(rollbackOn = ALL_EXCEPTIONS).

⚠️ Do not put @Transactional on controllers or private helpers

Keep transaction boundaries on public service methods that represent one unit of work. On a private helper the annotation does nothing; on controllers it stretches transactions across network I/O.

Validation: @Valid vs @Validated

Bean Validation annotations such as @NotNull, @NotBlank, @Size and @Email come from jakarta.validation.constraints. Spring Boot does not include a validator by default, so add spring-boot-starter-validation, which brings in Hibernate Validator.

import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;

public record CreateOrderRequest(
        @NotBlank @Email String customerEmail,
        @NotNull @Size(min = 1, max = 50) List<@Valid OrderLineRequest> lines) {
}

In a controller, @Valid @RequestBody validates the object and raises MethodArgumentNotValidException on failure. Constraint annotations placed directly on handler parameters, such as @RequestParam @Min(1) int page, trigger Spring MVC’s built-in method validation, added in Spring Framework 6.1, which raises HandlerMethodValidationException. The Spring reference adds a caution: a class-level @Validated on a controller switches to AOP-based method validation instead, so remove it to use the built-in support. @Validated remains the right choice on @ConfigurationProperties classes and on services where you need validation groups.

Scheduling and async: @Scheduled and @Async

Both are off until enabled on a configuration class.

@Configuration
@EnableScheduling
@EnableAsync
public class BackgroundConfig {
}

@Component
public class ReportJobs {

    private final ReportService reports;

    public ReportJobs(ReportService reports) {
        this.reports = reports;
    }

    @Scheduled(cron = "0 0 2 * * *", zone = "Asia/Kolkata")
    public void nightlySalesReport() {
        reports.generateDaily();
    }

    @Scheduled(fixedDelay = 300_000)
    public void retryFailedWebhooks() {
        reports.retryWebhooks();
    }
}

@Service
public class EmailService {

    @Async
    public CompletableFuture<Void> sendReceipt(Long orderId) {
        // runs on a task executor thread
        return CompletableFuture.completedFuture(null);
    }
}

Spring cron expressions have six fields, starting with seconds, and zone matters for teams serving India and the USA. @Async called from the same class runs synchronously, and in a cluster every instance runs every @Scheduled method.

Caching: @Cacheable and @CacheEvict

Add @EnableCaching to a configuration class, then annotate read methods with @Cacheable and write methods with @CacheEvict. Without a cache library on the classpath, Spring Boot falls back to a simple in-memory map, which is fine for development but not for multiple instances.

@Service
public class ProductService {

    @Cacheable("products")
    public ProductDto find(Long id) {
        return loadFromDatabase(id);
    }

    @CacheEvict(cacheNames = "products", allEntries = true)
    public ProductDto update(ProductDto product) {
        return save(product);
    }
}

Internal calls skip the cache. Cache keys that refer to parameter names, such as key = "#id", rely on the compiler’s -parameters flag, which spring-boot-starter-parent and the Spring Boot Gradle plugin configure for you; builds without it can fail to resolve the names.

Method security: @EnableMethodSecurity and @PreAuthorize

Spring Security’s reference states that the Spring Boot security starter does not enable method-level authorisation by default. Add @EnableMethodSecurity to a configuration class; it turns on @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter by default. The older @EnableGlobalMethodSecurity is deprecated, and the documentation encourages migration.

@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}

@Service
public class RefundService {

    @PreAuthorize("hasRole('ADMIN')")
    public void issueRefund(Long orderId) {
        // only runs if the caller has ROLE_ADMIN
    }
}

Method security is built on Spring AOP, so the self-invocation rule applies again: an internal call to issueRefund skips the check. Keep URL-level rules in your SecurityFilterChain as a first layer.

Testing annotations: @SpringBootTest, @WebMvcTest, @DataJpaTest and @MockitoBean

@SpringBootTest starts the whole application context, which suits a few end-to-end tests. Slices are faster: @WebMvcTest loads only the MVC layer (controllers, advice, filters, converters) and auto-configures MockMvc, while @DataJpaTest loads only JPA components.

The biggest recent change is mocking. Spring Boot’s @MockBean and @SpyBean were deprecated in 3.4.0 in favour of @MockitoBean and @MockitoSpyBean from Spring Framework’s org.springframework.test.context.bean.override.mockito package, and the Spring Boot API docs marked them for removal in 4.0.0. The Spring Boot 4 testing reference uses @MockitoBean throughout.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired
    MockMvc mvc;

    @MockitoBean
    OrderService service;

    @Test
    void returnsOrderAsJson() throws Exception {
        given(service.find(1L)).willReturn(new OrderDto(1L, "buyer@example.com"));

        mvc.perform(get("/api/orders/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.customerEmail").value("buyer@example.com"));
    }
}
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;

@DataJpaTest
class OrderRepositoryTest {

    @Autowired
    OrderRepository orders;

    @Test
    void findsOrdersByEmail() {
        // save a few orders, then assert on orders.findByCustomerEmail(...)
    }
}

Note the packages. In Spring Boot 3.x, @WebMvcTest lived in org.springframework.boot.test.autoconfigure.web.servlet and @DataJpaTest in org.springframework.boot.test.autoconfigure.orm.jpa. Spring Boot 4 splits test auto-configuration into technology-specific modules, so the imports change and you need the matching test modules on the classpath. @TestConfiguration adds test-only beans; as a nested class it supplements your main configuration rather than replacing it, and as a top-level class it must be brought in with @Import. Our white-box testing guide covers the wider technique.

A note on Lombok

Lombok is a third-party library, not part of Spring, but its annotations appear in many Spring Boot codebases. @RequiredArgsConstructor generates a constructor for final fields, which pairs neatly with constructor injection, and @Slf4j creates a logger. Be careful with @Data and generated equals/hashCode on JPA entities, because they can touch lazy relationships and behave oddly before an ID is assigned. Keep Lombok current with your JDK, and consider Java records for DTOs instead.

🎓 Expert Insight from Impex Infotech

Most annotation bugs we see in code reviews involve well-known annotations applied where the proxy cannot see them: @Transactional on a private method, @Async called from the same class. Before asking “which annotation do I need?”, ask “will this call come through a Spring proxy?”

05How AI Helps With Spring Boot Annotations

AI coding tools are now part of everyday development. The Stack Overflow 2026 Developer Survey, with more than 30,000 respondents, found that 73% of developers who use AI coding assistants or agents use them daily, and 66% of AI users work with coding agents. For Spring Boot, where much of the behaviour is declared rather than written, that help is useful but uneven. Models are good at the repetitive parts, such as mapping YAML to a properties class or writing test scaffolding, and less reliable on version-specific details and runtime behaviour. Here is how to use AI for Spring Boot work in a way that saves time without importing old habits.

Six practical AI workflows

  1. Explaining unfamiliar annotations in a legacy codebase. Inherited Spring applications often contain custom meta-annotations, old XML-era habits and conditionals nobody remembers adding. An assistant that can read the whole project can trace a custom annotation back to its definition, list the beans it affects and explain why a bean is or is not created. Ask it to cite file paths so you can verify each claim.
  2. Generating a @ConfigurationProperties class from application.yml. Give the assistant the YAML block and ask for a validated record, with appropriate types such as Duration and DataSize, plus the registration line. This is mechanical work AI does well, and the result is easy to check against the YAML.
  3. Writing slice tests. AI can draft a @WebMvcTest for each controller endpoint, including happy-path and validation-failure cases, or a @DataJpaTest for derived query methods. Tell it your Spring Boot version and insist on @MockitoBean, or you may get @MockBean from older training data.
  4. Migrating javax to jakarta and @MockBean to @MockitoBean. Agents can work through a module, change imports, update test annotations and rerun the build after each step. For large upgrades, combine this with the deterministic recipes described below, and use AI for the leftovers the recipes cannot handle.
  5. Reviewing @Transactional boundaries. Ask the assistant to list every transactional method, its propagation and rollback settings, and any call path where a transactional method is invoked through this, from a private method, or across a checked exception without rollbackFor. This turns a tedious review into a checklist you can verify.
  6. Generating validation constraints from requirements. Paste the field rules from a ticket (“email required, 1 to 50 line items, quantity at least 1”) and ask for a request record with Jakarta constraints and a matching test. Check edge cases such as @NotNull versus @NotBlank on strings.

Example prompts that work

Good prompts state the version, the namespace and the constraints. These three are written for any of the tools below.

We use Spring Boot 4.1, Java 21 and the jakarta.* namespace.
Convert this application.yml block into a @ConfigurationProperties record
with jakarta.validation constraints and @Validated. Use Duration for timeouts.
Show how to register it with @ConfigurationPropertiesScan. Do not use Lombok.

app:
  payments:
    base-url: https://payments.example.com
    timeout: 5s
    retries: 3
Write @WebMvcTest tests for OrderController (Spring Boot 4.1).
Use @MockitoBean (org.springframework.test.context.bean.override.mockito),
not @MockBean. Cover: GET /api/orders/{id} found and not found
(expect a ProblemDetail with status 404), and POST /api/orders
with an invalid email (expect 400). Use MockMvc and BDDMockito.
Review every @Transactional method in src/main/java.
For each one, report: class, method, visibility, propagation, readOnly,
rollbackFor, and whether any caller invokes it via this.method(...)
or from a private method. Flag checked exceptions that would not roll back.
Do not change code yet; output a table with file paths and line numbers.

The third prompt deliberately asks for analysis before edits. Reviewing a table is faster than reviewing a diff, and it keeps you in charge of design decisions such as where transaction boundaries belong.

The tools and what they do

The tools below are the ones Java teams most often ask us about. The descriptions stick to what each vendor’s own documentation says; this is not a ranking, and the right choice depends on your IDE, repository host and company policies.

  • GitHub Copilot offers inline code suggestions and chat in supported IDEs, an agent mode that picks files to change and proposes edits and terminal commands for approval, a cloud agent you can assign a GitHub issue to so it works on a branch and opens a pull request, and AI code review.
  • JetBrains AI Assistant works inside JetBrains IDEs such as IntelliJ IDEA. Its documentation lists chat, generating code, tests, commit messages and documentation, and explaining code, commits and runtime errors. Junie, JetBrains’ coding agent, writes a structured plan before changing code and lets you approve key actions; its site lists migrations such as Spring Boot upgrades among the tasks it can run.
  • Claude Code is Anthropic’s agentic assistant that runs in the terminal, with IDE extensions, a desktop app and a web version. According to its documentation it can read a project, edit files, run commands such as builds and tests, and verify results in a loop, with permission modes that control what it may do without asking.
  • Cursor describes itself as an AI-first code editor. Its documentation lists an Agent for codebase-wide changes, test generation and debugging, Tab completion, and Rules for customising how the AI behaves.

Whatever you choose, give the tool persistent project context: a rules or instructions file stating your Spring Boot version, Java version, preferred injection style, test conventions and banned annotations. That single file prevents most version-drift suggestions. If you are comparing AI building blocks more broadly, our roundup of AI frameworks and tools for developers and our explainer on what AI agents are give useful background.

OpenRewrite: deterministic migrations, not AI

For version upgrades, a rule-based tool is often a better first pass than a language model. OpenRewrite applies recipes that transform source code and build files predictably, so the same input always gives the same output. Its documentation lists org.openrewrite.java.spring.boot4.UpgradeSpringBoot_4_0, a composite recipe that updates build files and changes deprecated APIs, and that includes a step to replace @MockBean and @SpyBean. Note the licence: the documentation lists this recipe under the Moderne Source Available License, so check the terms for commercial use. A sensible order is recipes first, then compile and test, then use an AI agent on what is left, with a human reviewing the diff.

06Spring AI: Adding AI Features to a Spring Boot App

AI coding assistants help you write Spring code. Spring AI is different: it is a Spring project for adding AI features, such as chat, summarisation or document Q&A, to your own Spring Boot application. The project page describes it as “an application framework for AI engineering” and lists the current version as Spring AI 2.0.2. The 2.0.0 GA release, announced on 12 June 2026, was designed for Spring Boot 4.0 and 4.1 with Spring Framework 7.0.

According to the project page, Spring AI provides a portable API across AI model providers with synchronous and streaming options, structured output that maps model responses to Java objects, support for many vector databases through a common API, tool calling, Advisors that package common generative AI patterns, retrieval-augmented generation and chat memory, observability, and evaluation utilities. The main entry point is ChatClient, a fluent API in the style of RestClient. The 2.0 announcement also highlights Model Context Protocol support, including @McpTool, @McpResource and @McpPrompt annotations to expose Spring services as MCP endpoints, and lists the model providers the core project focuses on.

In practice, a Spring AI feature is just another bean: inject a ChatClient.Builder, build a client and call it from a service, with API keys in configuration properties. The usual annotations still apply: avoid holding a transaction open while waiting on a model, cache stable responses and protect admin prompts with method security. The API changed between 1.x and 2.0, so check the official reference before copying older examples. If you are planning a chatbot or AI feature on top of an existing backend, our teams for custom AI application development and AI chatbot development can help scope it.

07Risks of AI-Generated Spring Code

AI output is plausible by design, which makes its mistakes expensive. In Veracode’s 2025 GenAI Code Security Report, published on 30 July 2025, AI-generated code introduced security vulnerabilities in 45% of cases across more than 100 large language models and 80 coding tasks, and Java had the highest security failure rate of the languages tested, above 70%. The tasks were not Spring-specific, but in Spring Boot projects watch for:

  • Deprecated or retired annotations. @MockBean, @EnableGlobalMethodSecurity and WebSecurityConfigurerAdapter-style configuration appear in a lot of older training material.
  • Hallucinated annotations or attributes. Models sometimes invent plausible names or combine attributes from different annotations. If you cannot find it in the Javadoc, it does not exist.
  • Wrong imports. javax.persistence or javax.validation in a Spring Boot 3 or 4 project will not compile, and a wrong @Transactional import (jakarta.transaction.Transactional instead of Spring’s) changes which attributes are available.
  • Proxy blind spots. @Transactional, @Async or @Cacheable on private methods or invoked through this, which compile but do nothing.
  • Security misconfiguration. Overly broad permitAll() rules, CSRF disabled without a reason, secrets in application.yml, or @PreAuthorize added without @EnableMethodSecurity.

The fix is process: pin versions in your instructions, ask for official doc citations, run static analysis in CI and review AI changes like any pull request. The Stack Overflow survey found that 93% of respondents want source attribution before they trust what an AI gives them, which is a good standard for Spring code too.

08Common Mistakes, Symptoms and Fixes

Most of these produce no error at startup, which is why they cost so much debugging time.

Common Spring Boot annotation mistakes, how they show up and how to fix them
MistakeSymptomFix
Main class in a sub-packageControllers or services “not found”; 404s or missing bean errorsMove the @SpringBootApplication class to the root package
Checked exception in @Transactional methodPartial data committed after a failureAdd rollbackFor or throw an unchecked exception
Self-invoking a @Transactional, @Async or @Cacheable methodNo new transaction, synchronous execution, no cachingMove the method to another bean or restructure the call
@Transactional on a private methodMethod runs without a transactionMake it a public (or protected) method on a proxied bean
javax.* importsCompile errors after upgradingSwitch to jakarta.*; run a migration recipe
Using @MockBean on Boot 3.4+Deprecation warnings, then failures on Boot 4Use @MockitoBean / @MockitoSpyBean
Validation starter missing@Valid silently ignoredAdd spring-boot-starter-validation
Class-level @Validated on a controllerUnexpected ConstraintViolationException instead of MVC errorsRemove it to use built-in MVC method validation
Two beans of one type, no qualifierNoUniqueBeanDefinitionException at startupAdd @Primary or @Qualifier
@ConfigurationProperties class not registeredBean not found or values not boundAdd @ConfigurationPropertiesScan or @EnableConfigurationProperties
@PreAuthorize without @EnableMethodSecuritySecurity rule ignoredEnable method security in a configuration class
@Scheduled job in a multi-instance deploymentJob runs once per instanceUse a distributed lock or external scheduler

09Spring Boot Annotations Interview Questions: Quick Answers

Interviewers tend to probe the same handful of concepts. Short, precise answers work best.

  • What does @SpringBootApplication do? It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan, scanning from the annotated class’s package.
  • @Component vs @Service vs @Repository? All register beans; @Service signals business logic and @Repository adds persistence exception translation.
  • @Controller vs @RestController? @RestController adds @ResponseBody, so return values become the response body instead of view names.
  • Why constructor injection? Immutable, explicit dependencies and easy unit testing.
  • @Qualifier vs @Primary? @Primary sets the default; @Qualifier picks a specific bean at the injection point and wins over @Primary.
  • When does @Transactional roll back? By default on RuntimeException and Error; checked exceptions need rollbackFor.
  • @WebMvcTest vs @SpringBootTest? A slice of the web layer with MockMvc versus the full application context.
💡 Interview tip

When you answer a proxy-related question, mention self-invocation unprompted. It shows you have debugged real Spring applications, not just read about them.

10How Impex Infotech Can Help

Impex Infotech is a web, app and AI development company with offices in Rajkot, India and Marayong, NSW, working with clients in India, Australia, the USA and Canada. We build web applications and custom AI applications, and can help founders and CTOs plan a backend or add AI features to an existing product. For structuring a new product, see our guide to developing a SaaS application is a good starting point, and our portfolio shows the kinds of projects we deliver.

11Frequently Asked Questions

What are the most important Spring Boot annotations?

@SpringBootApplication, @Service, @RestController, @GetMapping, @RequestBody, @ConfigurationProperties, @Transactional, @Valid, @Entity, @WebMvcTest and @MockitoBean.

Which Spring Boot version should I use in 2026?

The current 4.1.x line, which requires Java 17 or later. Upgrade 3.x applications with the official migration guide.

Is @Autowired still needed?

Not on a class with a single constructor; Spring uses that constructor automatically. It is still needed when a class has several constructors.

Does @Transactional roll back on every exception?

No. By default it rolls back on unchecked exceptions and errors only. Use rollbackFor for checked exceptions, or configure a global rule with @EnableTransactionManagement(rollbackOn = ALL_EXCEPTIONS) on Spring Framework 6.2 or later.

What is the difference between @Valid and @Validated?

@Valid is the Jakarta standard for cascading validation. @Validated is Spring’s variant with validation groups, used on @ConfigurationProperties classes.

Is @MockBean removed in Spring Boot 4?

It was deprecated in Spring Boot 3.4 and marked for removal in 4.0. Use @MockitoBean and @MockitoSpyBean from org.springframework.test.context.bean.override.mockito instead.

Can AI write Spring Boot code reliably?

It drafts boilerplate, tests and migrations quickly but may suggest deprecated annotations, javax imports or insecure defaults. State your versions and review the output.

What is Spring AI and do I need it?

Spring AI is the Spring project for adding AI features, such as chat and retrieval-augmented generation, to Spring applications through APIs like ChatClient. It is not a coding assistant.

Planning a backend or adding AI to your product?

Talk to Impex Infotech about your web application or AI feature. We will help you scope the work, choose a sensible architecture and plan the build.

Get a Free Consultation →

12References

  1. Spring, Spring Boot project page (checked 28 Oct 2026). Current version 4.1.2 (sections 01, FAQ).
  2. Spring Blog, Spring Boot 4.1.0 available now (10 Jun 2026). 4.1.0 release date and highlights (section 01).
  3. Spring Boot documentation, System Requirements (4.1). Java 17 to 27, Spring Framework 7.0.10+, build tools, Servlet 6.1 containers (section 01).
  4. Spring Boot, Spring Boot 4.0 Release Notes (GitHub wiki). Jakarta Servlet 6.1, Persistence 3.2, Validation 3.1 upgrades; Jackson 3 (sections 01, 04).
  5. InfoQ, Spring Framework 7 and Spring Boot 4 (November 2025). Release timing, JDK 17 baseline, Jakarta EE 11 baseline, removal of javax.annotation/javax.inject support (section 01).
  6. Spring Boot documentation, Using the @SpringBootApplication Annotation (4.1.2). The three features it enables (sections 04, 09).
  7. Spring Framework documentation, Proxying Mechanisms (7.0.10). Self-invocation, private and final methods (sections 02, 04).
  8. Spring Framework documentation, Using @Transactional. Defaults, method visibility since 6.0, self-invocation, rollbackOn since 6.2 (section 04).
  9. Spring Framework documentation, Rolling Back a Declarative Transaction. Default rollback on unchecked exceptions and errors; rollbackFor (section 04).
  10. Spring Framework documentation, Error Responses. ProblemDetail, RFC 9457, ResponseEntityExceptionHandler, spring.mvc.problemdetails.enabled (section 04).
  11. Spring Framework documentation, Validation (Spring MVC). MethodArgumentNotValidException, built-in method validation, class-level @Validated caution (section 04).
  12. Spring Boot API, @ConfigurationProperties and @ConditionalOnMissingBean (4.1.2). Binding, no SpEL, auto-configuration-only recommendation (section 04).
  13. Spring Security documentation, Method Security. @EnableMethodSecurity defaults, @EnableGlobalMethodSecurity deprecation, starter not enabling method security (section 04).
  14. Spring Boot documentation, Testing Spring Boot Applications (4.0) and DataJpaTest package listing. @SpringBootTest, @WebMvcTest module and package, @MockitoBean, @TestConfiguration (section 04).
  15. Spring Boot API, spring-boot-test 3.4.0 deprecated list and MockBean API. Deprecation since 3.4.0 in favour of MockitoBean, marked for removal in 4.0.0 (sections 04, 08, FAQ).
  16. OpenRewrite, Migrate to Spring Boot 4.0 (Community Edition). Recipe name, scope, MockBean replacement step, licence (section 05).
  17. Spring, Spring AI project page (checked 28 Oct 2026) and Spring Blog, Spring AI 2.0.0 GA Available Now (12 Jun 2026). Version 2.0.2, features, ChatClient, MCP annotations, Boot 4 baseline (section 06).
  18. Stack Overflow Blog, The results of the 2026 Developer Survey are here (6 Oct 2026). 73% daily use, 66% coding agents, 93% source attribution, 30,000+ respondents (sections 05, 07).
  19. Veracode, AI-Generated Code Poses Major Security Risks in Nearly Half of All Development Tasks (30 Jul 2025). 45% vulnerability rate, 100+ LLMs, 80 tasks, Java above 70% (section 07).
  20. GitHub Docs, GitHub Copilot features. Inline suggestions, chat, agent mode, cloud agent, code review (section 05).
  21. JetBrains, JetBrains AI Assistant documentation and Junie. AI Assistant capabilities; Junie planning, approvals and migrations (section 05).
  22. Anthropic, How Claude Code works. Agentic loop, tools, interfaces, permission modes (section 05).
  23. Cursor, Cursor documentation: Introduction. Agent, Tab and Rules (section 05).

Recent Posts

Spring Boot Annotations List With Examples
Software Management
By Varun Avlani / October 30, 2026

Spring Boot Annotations List With Examples

Spring Boot Annotations: The Complete 2026 Guide With Examples (and How AI Helps You Use Them Correctly) ⏱ 24 min...

Read More
Inventory Management Software Solutions Small Business
Software Management
By Varun Avlani / October 30, 2026

Inventory Management Software Solutions Small Business

Best Inventory Management Software Solutions for Small Business in 2026: Pricing, Features and When to Go Custom (USA & India)...

Read More
Amazon Web Hosting AWS Cloud Computing
AWS Cloud Computing
By Varun Avlani / October 30, 2026

Amazon Web Hosting AWS Cloud Computing

Amazon Web Hosting (AWS) in 2026: How Cloud Hosting Works, What It Really Costs and How to Host Your Website...

Read More

Recent Posts

Spring Boot Annotations List With Examples
Software Management
By Varun Avlani / October 30, 2026

Spring Boot Annotations List With Examples

Spring Boot Annotations: The Complete 2026 Guide With Examples (and How AI Helps You Use Them Correctly) ⏱ 24 min...

Read More
Inventory Management Software Solutions Small Business
Software Management
By Varun Avlani / October 30, 2026

Inventory Management Software Solutions Small Business

Best Inventory Management Software Solutions for Small Business in 2026: Pricing, Features and When to Go Custom (USA & India)...

Read More
Amazon Web Hosting AWS Cloud Computing
AWS Cloud Computing
By Varun Avlani / October 30, 2026

Amazon Web Hosting AWS Cloud Computing

Amazon Web Hosting (AWS) in 2026: How Cloud Hosting Works, What It Really Costs and How to Host Your Website...

Read More