Java Collections Framework

 The Java Collections Framework (JCF) is a powerful architecture provided in the java.util package for storing, retrieving, and manipulating groups of objects efficiently. It offers a set of interfaces, classes, and algorithms that streamline data handling by eliminating the need to write custom data structures from scratch.

Key Features

  • Rich Set of Data Structures: Includes core structures like List, Set, Queue, and Map for managing different types of collections.

  • Reusable and Efficient: Provides ready-made, optimized implementations such as ArrayList, HashSet, LinkedList, TreeMap, etc.

  • Thread-Safe Variants: Offers concurrent and synchronized versions (e.g., ConcurrentHashMap, Collections.synchronizedList) for multi-threaded environments.

  • Generic Support: Seamless integration with generics, enhancing type safety and reducing runtime errors.

  • Functional Programming Integration: Fully compatible with lambda expressions and the Stream API, enabling modern, declarative data processing.

  • Algorithm Support: Comes with utility methods in the Collections class for sorting, shuffling, reversing, searching, and filling collections.



Java Versions

Java LTS Versions: Java 8, Java 11, Java 17, Java 21

These are official Long-Term Support (LTS) releases provided by Oracle and other vendors like OpenJDK, Amazon Corretto, Azul Zulu, and Eclipse Temurin.

  • Recommended for production environments due to their extended support lifecycle (typically 8+ years).

  • Oracle formalized the LTS model with Java 11, introducing a new LTS release every 3 years.

  • Java 8, though released before the formal LTS model was introduced, is widely regarded as an LTS version because of its long-term support and broad adoption.

  • LTS (Long-Term Support) ensures continued updates including: Security patches, Bug fixes, Performance enhancements


Java Non-LTS Versions: Java 1.2, 5, 6, 7, 9, 10, 12, 13, 14, 15, 16, 18, 19, 20, etc.

These are feature releases with a shorter support window (~6 months), released between LTS versions.

  • Designed to introduce new features and improvements early.

  • Useful for developers to experiment before features stabilize in future LTS versions.

  • Java 6 and 7, despite having extended support in practice, were not officially classified as LTS.



Below is a list of Java versions along with their key features.

🔹 Java 1.0 (Jan 1996)

  • First official release.

  • Introduced platform independence via the Java Virtual Machine (JVM).

  • Provided automatic memory management through built-in garbage collection.

  • Enabled object-oriented programming with classes and interfaces.

  • Supported multithreading with Thread and Runnable.

  • Included exception handling with try, catch, finally, throw, and throws.

  • Introduced AWT (Abstract Window Toolkit) for building basic GUI applications.

  • Introduced applets to run Java programs securely inside web browsers.

  • Provided networking support via java.net (sockets, URLs, etc.).

  • Included input/output (I/O) via java.io with stream-based I/O.

  • Included core utility classes in java.util (e.g., Vector, Hashtable, Date).

  • Defined primitive data types: byte, short, int, long, float, double, char, boolean.

  • Provided core language classes in java.lang (e.g., Object, String, Math, System).

  • Introduced basic security model (sandbox) for running untrusted code safely.

  • Used compiled bytecode (.class files) executed by the JVM.

  • Supported Unicode 1.1 character encoding for internationalization.

  • Allowed dynamic class loading at runtime.


🔹 Java 1.1 (Feb 1997)

  • Introduced Event Delegation Model to replace the old AWT event model.

  • Added Inner Classes, including static, member, local, and anonymous classes.

  • Introduced JavaBeans component model for reusable software components.

  • Added Reflection API (java.lang.reflect) for runtime inspection and manipulation of classes.

  • Introduced RMI (Remote Method Invocation) for distributed object communication in pure Java.

  • Added Object Serialization (java.io.Serializable) to persist and restore object states.

  • Introduced JDBC 1.0 for database connectivity via SQL.

  • Enhanced Internationalization support with java.util.Locale and ResourceBundle.

  • Enabled Security enhancements, including digital signing and key management.

  • Added support for Unicode 2.0 for broader character encoding.

  • Introduced javac support for -target flag for cross-compilation to earlier versions.

  • Expanded AWT improvements for layout managers, printing, and clipboard support.

  • Added JAR file format support for packaging classes and resources together.


🔹 Java 1.2 (Dec 1998) – Java 2 

 ðŸ‘‰ Non-LTS but popular and widely adopted, as LTS wasn’t officially defined back then.

  • Introduced the Collections Framework (List, Set, Map, etc.) under java.util.

  • Added the Swing GUI toolkit (javax.swing) for richer, lightweight UI components.

  • Launched the Java Plug-in to run applets within web browsers securely.

  • Introduced the Java 2 Security Model with fine-grained, policy-based permissions.

  • Introduced the Access Control API (java.security) with Permission, Policy, etc.

  • Enhanced JIT (Just-In-Time) Compiler for better performance.

  • Introduced Java IDL for CORBA interoperability and distributed computing.

  • Improved Internationalization (i18n) and Localization features.

  • Added support for Drag and Drop (DnD) and Clipboard APIs.

  • Introduced Weak References and java.lang.ref package.

  • Introduced Java Naming and Directory Interface (JNDI) for directory services.

  • Enhanced AWT with lightweight component architecture.

  • Introduced ScrollPane, ToolTip, and other advanced GUI components.

  • Deprecated old event model fully in favor of event delegation model.

  • Added support for serialization filtering (basic implementation for secure deserialization).

  • Introduced Policy-based security management for better control over code access.

  • Java 2 Platform split into J2SE, J2EE, and J2ME editions.


🔹 Java 1.3 (May 2000)

  • Introduced HotSpot JVM as the default virtual machine for better performance.

  • Added Java Sound API (javax.sound) for playback and recording of audio.

  • Introduced Java Naming and Directory Interface (JNDI) to core API (javax.naming).

  • Enhanced RMI (Remote Method Invocation) with RMI over IIOP (Inter-ORB Protocol).

  • Improved Swing performance and look & feel updates.

  • Introduced Mouse Wheel Support in AWT and Swing (MouseWheelEvent).

  • Added Dynamic Proxy Classes via java.lang.reflect.Proxy for flexible interface implementations.

  • Added Timer class in javax.swing for easier scheduling of UI tasks.

  • Introduced strictfp keyword to enforce IEEE 754 standards in floating-point computations.

  • Improved garbage collection algorithms and performance.

  • Enhanced Java Platform Debugger Architecture (JPDA) for better debugging tools.

  • Deprecated old thread methods like stop(), suspend(), and resume() for safety reasons.

  • Integrated JAR indexing for faster class loading in large archives.

  • Updated tooling: improved javac, java, javadoc, and other SDK tools.


🔹 Java 1.4 (Feb 2002)

  • Introduced the assert keyword for runtime assertions (assert condition;).

  • Added NIO (New I/O) package (java.nio) for high-performance I/O with buffers and channels.

  • Introduced regular expression support via java.util.regex package.

  • Integrated Logging API in java.util.logging for configurable application logging.

  • Added exception chaining with constructors that take a cause (Throwable).

  • Introduced image I/O APIs (javax.imageio) for reading/writing images.

  • Enhanced XML support via JAXP 1.1 (DOM, SAX, and XSLT).

  • Integrated IPv6 support into core networking APIs.

  • Added Preferences API (java.util.prefs) for storing user/system configuration data.

  • Improved Security APIs including cryptographic extensions and certificate support.

  • Enhanced Swing with improved focus handling, tool-tip management, and drag-and-drop.

  • Introduced non-blocking I/O and memory-mapped files in NIO.

  • Improved garbage collection and overall JVM performance.


🔹 Java 5 (Sep 2004) – aka Java 1.5, "Tiger" 

 ðŸ‘‰ Non-LTS but popular and widely adopted due to its major language enhancements

  • Introduced Generics (List<String>), enabling type-safe collections.

  • Introduced Enhanced for loop (for-each) for iterating over arrays and collections.

  • Added Autoboxing/Unboxing between primitives and wrapper classes (e.g., int ↔ Integer).

  • Introduced Typesafe Enums using the enum keyword.

  • Added Varargs (...) to support variable-length method arguments.

  • Introduced Annotations (Metadata) using @interface, enabling tools and frameworks support.

  • Added Static Import (import static) to allow static members to be used without class prefix.

  • Improved Concurrency API in java.util.concurrent (Executors, Locks, atomic variables).

  • Enhanced JVM performance and class loading mechanism.

  • Introduced Formatted output (System.out.printf) via java.util.Formatter.

  • Added Scanner class for simplified console input (java.util.Scanner).

  • Updated Java Memory Model for better thread visibility and correctness.

  • Improved instrumentation and monitoring APIs for profiling and debugging.


🔹 Java 6 (Dec 2006) – "Mustang"

 ðŸ‘‰ Non-LTS but popular and widely adopted due to its performance improvements and enhanced developer tools.

  • Integrated Java Compiler API (javax.tools) for compiling Java code at runtime.

  • Introduced Scripting support via javax.script (JSR 223) for running dynamic languages like JavaScript.

  • Added JDBC 4.0 with features like automatic driver loading and SQL exception chaining.

  • Improved Web Services support with built-in JAX-WS 2.0 and JAXB 2.0 APIs.

  • Enhanced Monitoring and Management with better JMX (Java Management Extensions).

  • Added support for Pluggable Annotations Processing API (javax.annotation.processing).

  • Updated Swing GUI with better system tray support and table sorting/filtering.

  • Enhanced Performance of JVM, especially startup time and garbage collection.

  • Integrated Windows Vista support and native look & feel updates.

  • Improved Java Web Start and Java Deployment Toolkit.

  • Removed support for older APIs and deprecated features (e.g., old CORBA APIs).

  • Upgraded JavaScript engine to Rhino for better scripting performance.

  • Introduced Thread dump on Ctrl+Break and better debugging support.


🔹 Java 7 (Jul 2011) – "Dolphin"

 ðŸ‘‰ Non-LTS but popular and widely adopted due to its language enhancements and NIO.2 API improvements.

  • Introduced try-with-resources for automatic resource management (ARM) with AutoCloseable.

  • Added diamond operator (<>) to simplify generic instance creation.

  • Enabled multi-catch in exception handling (catch (IOException | SQLException e)).

  • Improved type inference and added underscores in numeric literals for readability.

  • Added Strings in switch statements for better control flow.

  • Introduced binary literals using prefix 0b (e.g., 0b1010).

  • Introduced NIO.2 (New I/O) with java.nio.file package for file system access and watch service.

  • Enhanced Fork/Join framework for parallelism in java.util.concurrent.

  • Included JDBC 4.1 with enhanced capabilities.

  • Upgraded Locale and Unicode support to Unicode 6.0.

  • Improved class-loader architecture (ClassLoader close method and hierarchy fixes).

  • Integrated InvokeDynamic bytecode instruction to support dynamic languages on the JVM.

  • Deprecated some old APIs and provided cleaner replacements (like for file I/O).

  • Added support for IPv6 in new network APIs.

  • Improved performance, garbage collection, and support for multi-core systems.


🔹 Java 8 (Mar 2014) 

 ðŸ‘‰ LTS release, extremely popular and widely adopted due to groundbreaking features like Lambda expressions, Streams API, and the new Date-Time API.

  • Introduced Lambda Expressions for writing anonymous functions concisely.

  • Added Streams API (java.util.stream) for functional-style processing of collections.

  • Introduced Functional Interfaces (e.g., Predicate, Function, Consumer) and @FunctionalInterface annotation.

  • Added Default and Static Methods in Interfaces to support backward compatibility.

  • Introduced java.time (Date and Time API), a modern replacement for Date and Calendar.

  • Added Optional<T> to avoid null references and express optional values.

  • Introduced Nashorn JavaScript Engine for embedding JavaScript in Java applications.

  • Enhanced Collectors API for advanced aggregation (Collectors.toList(), joining(), etc.).

  • Improved type inference for generic methods and lambdas.

  • Added Repeatable Annotations using @Repeatable.

  • Introduced Method References (ClassName::methodName) as shorthand for lambdas.

  • Added CompletableFuture and enhancements to java.util.concurrent for better async programming.

  • Enhanced parallel processing using parallel streams.

  • Introduced Base64 encoding/decoding utility in java.util.Base64.

  • Provided new security and performance improvements under the hood.


🔹 Java 9 (Sep 2017)

  • Introduced Java Platform Module System (JPMS), also known as Project Jigsaw, for modularizing the JDK and applications.

  • Added jshell (REPL) tool for interactive Java execution and experimentation.

  • Introduced var-like private interface methods to support better code reuse (private methods in interfaces).

  • Improved Stream API with new methods like takeWhile(), dropWhile(), iterate().

  • Added Optional enhancements including ifPresentOrElse(), or().

  • Introduced Factory methods for immutable collections (List.of(), Set.of(), Map.of()).

  • Enhanced Process API (java.lang.ProcessHandle) to manage OS-level processes better.

  • Introduced Multi-release JARs to support different versions of class files in one JAR.

  • Improved JVM performance with a more compact string representation ("compact strings").

  • Added Segmented Code Cache for better memory management of compiled code.

  • Deprecated the CMS Garbage Collector (in preparation for removal).

  • Introduced Platform logging API (System.Logger) as a lightweight logging alternative.

  • Improved stack-walking API (StackWalker) for efficient and flexible access to call stacks.

  • Enhanced Unicode 8.0 support and locale data.


🔹 Java 10 (Mar 2018)

  • Introduced var keyword for local variable type inference.

  • Added Application Class-Data Sharing (AppCDS) to improve startup performance and reduce memory footprint.

  • Introduced Garbage-Collector Interface to allow plug-and-play GC implementations.

  • Enhanced container awareness in JVM (for memory and CPU limits, important for Docker/Kubernetes).

  • Added Parallel Full GC for better performance with G1 Garbage Collector.

  • Introduced Thread-local handshakes to improve thread management and safe point operations.

  • Improved JVM compilation repository for better diagnostic information.

  • Consolidated JDK source code repository into a single Git repo.

  • Enabled Heap allocation on alternative memory devices (e.g., NV-DIMMs).

  • Marked javah tool as removed, fully integrated native header generation into javac.


🔹 Java 11 (Sep 2018)

 ðŸ‘‰ LTS release, widely adopted for long-term support and key additions like the HTTP Client API, var in lambda parameters, and removal of outdated modules.

  • Introduced var in lambda parameters for consistency and annotations.
  • Added new String methods: isBlank(), lines(), strip(), repeat().

  • Added new File methods: readString(), writeString() in Files class.

  • Introduced HttpClient API (standardized from incubator module in Java 9) for HTTP/2 and async requests.

  • Added Collection.toArray(IntFunction) method for easier array conversions.

  • Introduced Nest-based access control to improve access between nested classes.

  • Added Flight Recorder (JFR) for low-overhead profiling and diagnostics.

  • Added Z Garbage Collector (ZGC) – scalable low-latency GC (experimental).

  • Removed several legacy and deprecated modules/APIs, including:

    • Java EE modules (java.xml.ws, java.activation, etc.)

    • CORBA and related APIs

    • java.se.ee aggregate module

  • Removed the javaws (Java Web Start) and appletviewer tools.

  • Removed javah tool (already deprecated in Java 10).

  • Introduced Launch Single-File Source-Code Programs using java MyApp.java.


🔹 Java 12 (Mar 2019)

  • Introduced Switch Expressions (Preview) to simplify switch syntax and make it more expression-oriented.

  • Added JVM Constants API (java.lang.constant) for working with class file constants.

  • Introduced Shenandoah Garbage Collector (Experimental) – low-pause-time GC for large heaps.

  • Improved G1 Garbage Collector to return unused heap memory to the OS.

  • Added Microbenchmarking support with the JMH-like jdk.microbenchmark module (for internal benchmarking).

  • Improved default CDS (Class Data Sharing) archives to include system classes automatically.

  • Enhanced JVM startup and footprint by refining default class data sharing setup.

  • Improved error reporting and heap diagnostics, including detailed NullPointerException messages (experimental flag).


🔹 Java 13 (Sep 2019)

  • Introduced Text Blocks (Preview) to simplify writing multi-line string literals using """.

  • Enhanced Switch Expressions (Preview) with yield for returning values from blocks.

  • Added Dynamic CDS Archives to improve application startup by enabling CDS after initial runs.

  • Reimplemented the legacy Socket API for better maintainability and performance.

  • Improved Z Garbage Collector (ZGC) by uncommitting unused memory back to the OS.


🔹 Java 14 (Mar 2020)

  • Finalized Switch Expressions (switch as expression with yield).

  • Introduced Records (Preview) to simplify data carrier classes (record Point(int x, int y)).

  • Introduced Pattern Matching for instanceof (Preview) for cleaner type checks and casting.

  • Added Helpful NullPointerExceptions with detailed messages showing what was null.

  • Introduced jdk.foreign API (Incubator) for foreign-memory access outside the JVM heap.

  • Added jpackage tool for packaging self-contained Java applications.

  • Enhanced NVM support for Java heap on persistent memory devices.

  • Improved Garbage Collectors:

    • ZGC: Supports return of unused memory to OS (macOS, Windows support added).

    • G1 GC: Optimized heap region pinning.

  • Deprecated and removed several outdated CMS GC and other legacy features.


🔹 Java 15 (Sep 2020)

  • Finalized Text Blocks (""") for multi-line, readable string literals.

  • Introduced Sealed Classes (Preview) to restrict class inheritance explicitly.

  • Introduced Hidden Classes for dynamic frameworks and improved JVM performance.

  • Added EdDSA (Edwards-Curve Digital Signature Algorithm) for modern cryptographic support.

  • Enhanced Z Garbage Collector (ZGC) with support for macOS and Windows.

  • Removed the Nashorn JavaScript Engine (deprecated in Java 11).

  • Removed RMI Activation system (outdated remote object lifecycle management).

  • Re-implemented java.util.Random subclass SplittableRandom for better statistical properties.

  • Upgraded Garbage Collection (G1 and ZGC) and improved memory management.

  • Replaced legacy DatagramSocket API implementation with a modern, more maintainable version.


🔹 Java 16 (Mar 2021)

  • Finalized Records for compact, immutable data classes (record Point(int x, int y)).

  • Finalized Pattern Matching for instanceof for cleaner and safer type checks.

  • Added jdk.incubator.foreign API (Foreign Linker and Memory Access API, incubator).

  • Introduced Sealed Classes (Second Preview) to control which classes can extend or implement a type.

  • Added Packaging Tool (jpackage) for native installers across platforms.

  • Enabled Concurrent Thread-Stack Processing in the JVM for better performance.

  • Migrated Java source code to Git and GitHub (OpenJDK project).

  • Made the Z Garbage Collector (ZGC) concurrent class unloading capable.

  • Added Unix-Domain Socket Channel API to the standard library.

  • Strongly encapsulated JDK internal APIs, warning when reflective access is used.

  • Enabled C++14 language features in HotSpot for JVM code base modernization.

  • Enhanced Windows support (especially Windows/AArch64 port).


🔹 Java 17 (Sep 2021)

 ðŸ‘‰ LTS release, widely adopted for stabilizing modern features like sealed classes, pattern matching, and enhanced performance and security.

  • Finalized Sealed Classes to restrict inheritance and improve modeling.

  • Finalized Pattern Matching for instanceof for simplified type casting.

  • Finalized Enhanced switch expressions from earlier previews.

  • Introduced Foreign Function & Memory API (Incubator) to interact with native code.

  • Introduced Strong encapsulation of JDK internals by default (except for critical reflection).

  • Added java.util.random package with new random number generators (LXM, Xoshiro, SplitMix).

  • Introduced New macOS rendering pipeline based on Apple’s Metal API.

  • Removed RMI Activation, long deprecated in earlier versions.

  • Removed Experimental AOT and JIT compiler (jaotc, Graal-based).

  • Removed Applets and appletviewer tool, formally ending browser-based Java.

  • Integrated Context-specific deserialization filters to boost serialization security.

  • Enhanced Performance, startup time, and GC behavior (ZGC and G1 improvements).

  • Made JEP 356: Enhanced Pseudo-Random Number Generators standard.


🔹 Java 18 (Mar 2022)

  • Introduced Simple Web Server (jwebserver) for prototyping and testing static content.

  • Introduced UTF-8 as the default charset for the standard Java APIs.

  • Added Code Snippets in JavaDoc with the new @snippet tag for richer documentation.

  • Introduced Vector API (Third Incubator) for vectorized computations using SIMD hardware.

  • Introduced Foreign Function & Memory API (Second Incubator) to call native libraries without JNI.

  • Introduced Internet-Address Resolution SPI for custom DNS resolution implementations.

  • Introduced finalization deprecation warning as it will be removed in future versions.

  • Improved Security and Performance enhancements across the platform.

  • Continued JVM and garbage collector refinements (especially for G1, ZGC).


🔹 Java 19 (Sep 2022)

  • Introduced Virtual Threads (Preview) via Project Loom for lightweight, scalable concurrency.

  • Introduced Structured Concurrency (Incubator) to simplify multithreaded code and cancellation.

  • Added Record Patterns (Preview) for enhanced pattern matching and data deconstruction.

  • Added Pattern Matching for switch (Preview) for expressive and type-safe control flow.

  • Updated Foreign Function & Memory API (Third Incubator) with more stable design.

  • Continued incubation of Vector API (Fourth Incubator) for high-performance math operations.

  • Enhanced platform performance and GC tuning (notably for ZGC and G1).

  • Strengthened JDK security and modernized internal APIs.


🔹 Java 20 (Mar 2023)

  • Continued Virtual Threads (Second Preview) to simplify concurrency at scale.

  • Continued Structured Concurrency (Second Incubator) for managing thread lifecycles hierarchically.

  • Continued Record Patterns (Second Preview) for more powerful pattern matching.

  • Continued Pattern Matching for switch (Second Preview) for flexible and safe control flow.

  • Enhanced Foreign Function & Memory API (Fourth Incubator) with usability improvements.

  • Continued development of Vector API (Fifth Incubator) for vectorized math operations.

  • General performance, stability, and GC improvements across JVM subsystems.


🔹 Java 21 (Sep 2023)

 ðŸ‘‰ LTS release, popular for finalizing virtual threads, pattern matching, record patterns, and introducing modern APIs like string templates and sequenced collections.

  • Finalized Virtual Threads for lightweight concurrency via Project Loom.

  • Finalized Record Patterns for elegant deconstruction of record objects.

  • Finalized Pattern Matching for switch for safer and more expressive control flow.

  • Finalized Sequenced Collections API for ordered List, Set, and Map interfaces.

  • Finalized String Templates (Preview) for safer and more readable string interpolation.

  • Introduced Scoped Values (Preview) for safe, immutable data sharing with virtual threads.

  • Continued Foreign Function & Memory API (Third Preview) for efficient native code integration.

  • Enhanced Structured Concurrency (Preview) for better thread management.

  • Updated Vector API (Sixth Incubator) for advanced SIMD processing.

  • Improved Garbage Collection, JIT compilers, and overall JVM performance.

  • Removed deprecated legacy features and promoted stronger encapsulation of internal APIs.

    Spring Framework Annotations



    1. Spring (Core) Annotations


    @Component

    Definition: Marks a class as a Spring-managed component.

    Usage: Used for any generic component that needs to be auto-detected and registered in the application context.

    Example:

    @Component
    public class EmailValidator { public boolean isValid(String email) { return email.contains("@"); } }

    @Controller

    Definition: Indicates a class is a Spring MVC controller to handle web requests.

    Usage: Used in Spring MVC applications to define a web layer controller that returns views.

    Example:

    @Controller
    public class HomeController { @GetMapping("/") public String home() { return "index"; // returns view name } }

    @Service

    Definition: Specialized @Component used for service layer classes.

    Usage: Used to indicate a class contains business logic.

    Example:

    @Service
    public class PaymentService { public void processPayment() { // business logic here } }

    @Repository

    Definition: Specialized @Component used for persistence layer components.

    Usage: Enables automatic exception translation from JPA/Hibernate exceptions to Spring DataAccessException.

    Example:

    @Repository
    public class UserRepository { public void save(User user) { // save to DB } }

    @Configuration

    Definition: Marks a class as a source of Spring bean definitions.

    Usage: Used to define beans via Java-based configuration.

    Example:

    @Configuration
    public class AppConfig { @Bean public UserService userService() { return new UserService(); } }

    @Bean

    Definition: Declares a method that returns a bean to be managed by Spring.

    Usage: Used inside @Configuration-annotated classes to explicitly define beans.

    Example:

    @Bean
    public EmailService emailService() { return new EmailService(); }

    @Autowired

    Definition: Injects a dependency automatically by type.

    Usage: Used to auto-wire beans into a class’s fields or constructors.

    Example:

    @Autowired
    private PaymentService paymentService;

    @Qualifier

    Definition: Specifies the exact bean to inject when multiple candidates are present.

    Usage: Used with @Autowired to resolve ambiguity.

    Example:

    @Autowired
    @Qualifier("paypalService") private PaymentService paymentService;

    @Primary

    Definition: Indicates that a bean should be given preference during autowiring.

    Usage: Used when multiple beans of the same type exist, but one should be the default.

    Example:

    @Primary
    @Bean public PaymentService defaultPaymentService() { return new PaypalService(); }

    @Value

    Definition: Injects a value from the properties file or expression.

    Usage: Used to inject configuration values directly into beans.

    Example:

    @Value("${app.name}")
    private String appName;

    @Scope

    Definition: Defines the lifecycle scope of a bean (singleton, prototype, request, etc.).

    Usage: Used to create non-singleton beans.

    Example:

    @Scope("prototype")
    @Component public class ReportGenerator { }

    @Lazy

    Definition: Delays bean initialization until it is actually needed.

    Usage: Improves startup performance by lazy loading non-critical beans.

    Example:

    @Lazy
    @Component public class ExpensiveComponent { }

    @PostConstruct

    Definition: Marks a method to be executed after the bean is initialized.

    Usage: Used for initialization logic after dependency injection.

    Example:

    @PostConstruct
    public void init() { System.out.println("Bean initialized"); }

    @PreDestroy

    Definition: Marks a method to be called before the bean is destroyed.

    Usage: Used for cleanup logic before the bean is removed.

    Example:

    @PreDestroy
    public void destroy() { System.out.println("Cleaning up"); }



    2. Spring MVC (Web Layer) Annotations


    @RequestMapping

    Definition: Maps a specific HTTP request to a method in a controller.

    Usage: Can be used for class-level or method-level URL mappings.

    Example:

    @RequestMapping("/api")
    public class ApiController { @RequestMapping("/status") public String status() { return "OK"; } }

    @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping

    Definition: Shorthand for @RequestMapping with specific HTTP methods.

    Usage: Used to handle RESTful requests.

    Example:

    @GetMapping("/users")
    public List<User> getUsers() { return userService.getAll(); }

    @RequestParam

    Definition: Binds a request parameter to a method argument.

    Usage: Used to extract query parameters from a request.

    Example:

    @GetMapping("/greet")
    public String greet(@RequestParam String name) { return "Hello, " + name; }

    @PathVariable

    Definition: Binds a URI path variable to a method parameter.

    Usage: Used to extract dynamic segments from the URL.

    Example:

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) { return userService.findById(id); }

    @RequestBody

    Definition: Binds the body of an HTTP request to an object.

    Usage: Used for handling JSON/XML payloads.

    Example:

    @PostMapping("/users")
    public void createUser(@RequestBody User user) { userService.save(user); }

    @ResponseBody

    Definition: Indicates that the return value should be used as the response body.

    Usage: Typically used in REST APIs to return JSON/XML.

    Example:

    @ResponseBody
    @GetMapping("/ping") public String ping() { return "pong"; }

    @RestController

    Definition: A shortcut for @Controller + @ResponseBody.

    Usage: Used to create RESTful web services.

    Example:

    @RestController
    public class UserController { @GetMapping("/users") public List<User> allUsers() { return userService.getAll(); } }

    @RequestHeader

    Definition: Binds a method parameter to an HTTP header.

    Usage: Used to access request headers.

    Example:

    @GetMapping("/user-agent")
    public String getUserAgent(@RequestHeader("User-Agent") String userAgent) { return userAgent; }

    @CookieValue

    Definition: Binds a method parameter to a cookie value.

    Usage:
    Used to read cookies.

    Example:

    @GetMapping("/session")
    public String session(@CookieValue("sessionId") String sessionId) { return "Session: " + sessionId; }

    @SessionAttribute

    Definition: Binds a method parameter to a session attribute.

    Usage: Used to retrieve session-scoped data.

    Example:

    @GetMapping("/profile")
    public String profile(@SessionAttribute("user") User user) { return user.getName(); }

    @ModelAttribute

    Definition: Binds request parameters to model attributes or adds attributes to the model.

    Usage: Used in both controllers and methods to prepopulate form data.

    Example:

    @ModelAttribute("user")
    public User initUser() { return new User(); }

    @InitBinder

    Definition: Customizes data binding for request parameters.

    Usage: Used to register custom editors or formatters.

    Example:

    @InitBinder
    public void initBinder(WebDataBinder binder) { binder.setDisallowedFields("id"); }

    @ExceptionHandler


    Definition: It handle exceptions thrown by controller methods so instead of returning an error page or stack trace, you can customize the response (via @ControllerAdvice or @RestControllerAdvice).

    Example: If this exception happens in a controller, run this method instead of crashing!

    @RestController

    public class UserController {

        @GetMapping("/users/{id}")

        public User getUser(@PathVariable Long id) {

            // Simulate user not found

            throw new UserNotFoundException("User not found with ID: " + id);

        }

    }

    - Without @ExceptionHandler, Spring will return a 500 error and a big stack trace.

    @ControllerAdvice

    public class GlobalExceptionHandler {

        @ExceptionHandler(UserNotFoundException.class)

        public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {

            return ResponseEntity.status(HttpStatus.NOT_FOUND)

            .body(ex.getMessage());

        }

    }

    - Now, when UserNotFoundException is thrown:

    • It doesn’t crash the app.
    • Spring calls handleUserNotFound() method.
    • The client receives a 404 Not Found response with a friendly message.

    - Your custom exception class

    public class UserNotFoundException extends RuntimeException {

        public UserNotFoundException(String message) {

            super(message);

        }

    }

    Spring-Specific? Yes

    - You can define different methods for different exceptions (Multiple Exception Handlers)

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNPE(NullPointerException ex) {
        return ResponseEntity.status(400).body("Null error: " + ex.getMessage());
    }
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntime(RuntimeException ex) {
        return ResponseEntity.status(500).body("Unexpected error occurred");
    }


    Tip: Use @RestControllerAdvice for APIs that return JSON, and @ControllerAdvice for apps that return views (HTML pages).


    @ControllerAdvice


    Definition: Marks a class as a global exception handler, data binder, or model attribute provider for all controllers.

    Usage: Use this to centralize exception handling logic. 

    Example:

    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(IllegalArgumentException.class)
        public ResponseEntity<String> handleIllegalArg(IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("Invalid input");
        }
    }

    Spring-Specific? Yes


    @RestControllerAdvice


    Definition: A composed annotation combining @ControllerAdvice and @ResponseBody. Suitable for REST APIs.

    Usage: Used to return JSON/XML responses instead of view names when exceptions occur.

    Example:

    @RestControllerAdvice
    public class ApiExceptionHandler {
        @ExceptionHandler(Exception.class)
        public ResponseEntity<String> handleException(Exception e) {
            return ResponseEntity.status(500).body("Server Error: " + e.getMessage());
        }
    }
    Spring-Specific? Yes




    3. Spring Boot Annotations


    @SpringBootApplication

    Definition: Composite annotation combining @Configuration, @EnableAutoConfiguration, and @ComponentScan.

    Usage: Entry point for a Spring Boot application.

    Example:

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

    @EnableAutoConfiguration

    Definition: Tells Spring Boot to automatically configure beans based on classpath settings.

    Usage: Often included in @SpringBootApplication, but can be used separately if needed.

    Example:

    @EnableAutoConfiguration public class AppConfig { }

    @ComponentScan

    Definition: Specifies base packages to scan for annotated components.

    Usage: Used when components are in different packages not scanned by default.

    Example:

    @ComponentScan(basePackages = "com.example.services") public class AppConfig { }

    @ConfigurationProperties

    Definition: Maps properties defined in application.properties or application.yml to a Java class.

    Usage: Used to bind configuration properties to POJOs.

    Example:

    @Component
    @ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private int timeout; // getters and setters }

    @SpringBootTest

    Definition: Loads the full application context for integration tests.

    Usage: Used for writing Spring Boot integration or context tests.

    Example:

    @SpringBootTest public class ApplicationTests { @Test public void contextLoads() { } }

    @TestConfiguration

    Definition: Defines additional beans or config only used in tests.

    Usage: Useful to mock or replace certain beans during testing.

    Example:

    @TestConfiguration
    public class TestBeansConfig { @Bean public MyService testService() { return new MyServiceMock(); } }

    @RequestScope, @SessionScope, @ApplicationScope

    Definition: Declares bean scopes tied to HTTP request, session, or application context respectively.

    Usage: Used when different lifecycle control is needed for a bean.

    Example:

    @Component
    @RequestScope public class RequestLogger { public void log() { System.out.println("Request-scoped logger"); } }



    4. Spring Data & Persistence Annotations


    @Entity

    Definition: Marks a class as a JPA entity that maps to a database table.

    Usage: Used to indicate a class should be persisted in a relational database.

    Example:

    @Entity
    public class User { @Id private Long id; private String name; }

    @Table

    Definition: Specifies the table name mapped to the entity.

    Usage: Used to customize the table name or schema.

    Example:

    @Entity
    @Table(name = "users") public class User { ... }

    @Id

    Definition: Marks a field as the primary key.

    Usage: Mandatory for each entity to uniquely identify records.

    Example:

    @Id
    @GeneratedValue private Long id;

    @GeneratedValue

    Definition: Specifies how the primary key should be generated.

    Usage: Used in combination with @Id.

    Example:

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

    @Column

    Definition: Customizes mapping of a field to a column.

    Usage: Used to define column properties like name, length, nullable, etc.

    Example:

    @Column(name = "username", nullable = false, length = 50)
    private String name;

    @Transient

    Definition: Prevents a field from being persisted to the database.

    Usage: Useful for temporary or calculated fields.

    Example:

    @Transient
    private String sessionToken;

    @Lob

    Definition: Maps a large object (CLOB/BLOB) to the database.

    Usage: Used for large text or binary content.

    Example:

    @Lob
    private String longDescription;

    @Temporal

    Definition: Specifies the format for java.util.Date persistence.

    Usage: Used with legacy Date or Calendar objects.

    Example:

    @Temporal(TemporalType.DATE)
    private Date birthDate;

    @OneToOne, @OneToMany, @ManyToOne, @ManyToMany

    Definition: Define relationships between JPA entities.

    Usage: Used to model associations in object-relational mapping.

    Example:

    @OneToMany(mappedBy = "user")
    private List<Order> orders;

    @JoinColumn

    Definition: Specifies the foreign key column for relationships.

    Usage: Used with associations to define how tables are joined.

    Example:

    @ManyToOne
    @JoinColumn(name = "user_id") private User user;

    @MappedSuperclass

    Definition: Indicates a class whose fields are inherited by entities, but not a table itself.

    Usage: For base classes that share common fields like audit info.

    Example:

    @MappedSuperclass
    public abstract class Auditable { private LocalDateTime createdAt; }

    @Embeddable, and @Embedded

    Definition: Used to create component objects inside entities (value objects).

    Usage: Used to group fields into reusable embeddable objects.

    Example:

    @Embeddable
    public class Address { private String city; private String zip; } @Embedded private Address address;

    @Query

    Definition: Defines custom JPQL or native SQL queries on a repository method.

    Usage: Used when the default query derivation is not enough.

    Example:

    @Query("SELECT u FROM User u WHERE u.email = ?1")
    User findByEmail(String email);

    @Modifying

    Definition: Used on @Query methods that change data (e.g., update, delete).

    Usage: Tells Spring Data the query modifies data and is not read-only.

    Example:

    @Modifying
    @Query("DELETE FROM User u WHERE u.lastLogin < :cutoff") void deleteInactiveUsers(@Param("cutoff") LocalDate date);

    @Param

    Definition: Maps method parameters to query named parameters.

    Usage: Used inside @Query statements.

    Example:

    @Query("SELECT u FROM User u WHERE u.name = :name")
    User findByName(@Param("name") String name);

    @EnableJpaRepositories

    Definition: Enables JPA repositories by scanning packages.

    Usage: Placed on a configuration class to activate Spring Data JPA support.

    Example:

    @EnableJpaRepositories(basePackages = "com.example.repo")
    public class JpaConfig { }

    @RepositoryRestResource

    Definition: Exposes a Spring Data JPA repository as a REST endpoint.

    Usage: Used in Spring Data REST projects.

    Example:

    @RepositoryRestResource(path = "users")
    public interface UserRepository extends JpaRepository<User, Long> { }

    @Transactional

    Definition: Wraps a method or class with transaction boundaries.

    Usage: Used for methods interacting with the database.

    Example:

    @Transactional
    public void saveUser(User user) { userRepository.save(user); }

    @EnableTransactionManagement

    Definition: Enables support for the @Transactional annotation.

    Usage: Add to configuration class to enable declarative transactions.

    Example:

    @Configuration
    @EnableTransactionManagement public class TransactionConfig { }


    @Lock

    Definition: Applies a locking strategy (PESSIMISTIC or OPTIMISTIC) on a query.

    Usage: Used for concurrency control.

    Example:

    @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("SELECT u FROM User u WHERE u.id = :id") User findByIdForUpdate(@Param("id") Long id);

    Spring-Specific? No (JPA standard)



    5. Spring Caching Annotations


    @EnableCaching

    Definition: Enables Spring’s cache abstraction.

    Usage: Added to configuration class to allow caching annotations.

    Example:

    @Configuration
    @EnableCaching public class CacheConfig { }

    @Cacheable

    Definition: Caches the result of a method call.

    Usage: Used when repeated calls with the same parameters can return cached result.

    Example:

    @Cacheable("users")
    public User getUserById(Long id) { return userRepository.findById(id).orElse(null); }

    @CachePut

    Definition: Updates the cache with the latest method result.

    Usage: Used to force cache update when a method is invoked.

    Example:

    @CachePut("users")
    public User updateUser(User user) { return userRepository.save(user); }

    @CacheEvict

    Definition: Removes specific entries from the cache.

    Usage: Used when data is deleted or modified and must be removed from the cache.

    Example:

    @CacheEvict(value = "users", key = "#id")
    public void deleteUser(Long id) { userRepository.deleteById(id); }

    @Caching

    Definition: Combines multiple caching annotations on a single method.

    Usage: Useful when a method needs a combination of @CachePut, @CacheEvict, etc.

    Example:

    @Caching(
    evict = { @CacheEvict("users") }, put = { @CachePut("logs") } ) public void updateAndLog(User user) { // logic }



    6. Spring AOP Annotations


    @Aspect

    Definition: Marks a class as containing cross-cutting concerns (like logging, security, etc.).

    Usage: Used with @Before, @After, etc. to define advice.

    Example:

    @Aspect
    public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("Method called"); } }

    @Before, @After, @AfterReturning, @AfterThrowing, @Around

    Definition: Define when a method (advice) should be executed in relation to a join point (target method).

    Usage: Used for cross-cutting concerns such as logging, security, etc.

    Example:

    @Around("execution(* com.example..*(..))")
    public Object logExecution(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before execution"); Object result = joinPoint.proceed(); System.out.println("After execution"); return result; }

    @Pointcut

    Definition: Declares reusable pointcut expressions.

    Usage: Used to centralize expression definitions for @Before, @Around, etc.

    Example:

    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceMethods() { }



    7. Spring Scheduling & Async Execution Annotations


    @EnableScheduling

    Definition: Enables scheduled task execution.

    Usage: Added to config class to allow @Scheduled annotations.

    Example:

    @Configuration
    @EnableScheduling public class SchedulingConfig { }

    @Scheduled

    Definition: Schedules a method to be invoked at fixed intervals.

    Usage: Used for periodic jobs.

    Example:

    @Scheduled(fixedRate = 60000)
    public void runJob() { System.out.println("Running every 60 seconds"); }

    @EnableAsync

    Definition: Enables support for asynchronous method execution.

    Usage: Added to config class to allow @Async methods.

    Example:

    @Configuration
    @EnableAsync public class AsyncConfig { }

    @Async

    Definition: Indicates that a method should be executed asynchronously.

    Usage: Used to execute a method in a separate thread.

    Example:

    @Async
    public void sendNotificationEmail() { // send email in background }



    8. Spring Security Annotations


    @EnableWebSecurity

    Definition: Enables Spring Security’s web security support and allows customization via a WebSecurityConfigurerAdapter.

    Usage: Placed on a configuration class to activate Spring Security's auto-configuration for web applications.

    Example:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().authenticated();
        }
    }
    Spring-Specific? Yes


    @Secured

    Definition: Restricts method access to users who have specific roles.

    Usage: Used on service or controller methods to allow access only to users with given roles.

    Example:

    @Secured("ROLE_ADMIN") public void deleteUser(Long id) { // only accessible to admin users }

    Spring-Specific? No (Part of JSR-250, but enabled in Spring via @EnableGlobalMethodSecurity)


    @RolesAllowed

    Definition: Similar to @Secured; defines roles that are allowed to access a method.

    Usage: Used to restrict access using role-based authorization.

    Example:

    @RolesAllowed("ROLE_USER") public String viewProfile() { return "profile page"; }

    Spring-Specific? No (Standard JSR-250 annotation, supported in Spring with config)


    @PreAuthorize

    Definition: Evaluates a SpEL (Spring Expression Language) expression before method execution to determine access.

    Usage: Used for fine-grained access control on service methods or controller endpoints.

    Example:

    @PreAuthorize("hasRole('ADMIN')") public void createProject(Project p) { // only if caller has ADMIN role }

    Spring-Specific? Yes


    @PostAuthorize

    Definition: Evaluates a SpEL expression after method execution to determine whether access should be allowed.

    Usage: Used when you want to verify permissions after the method returns something (like a domain object).

    Example:

    @PostAuthorize("returnObject.owner == authentication.name") public Document getDocument(Long id) { return documentRepository.findById(id).orElse(null); }

    Spring-Specific? Yes


    @PreFilter (less common)

    Definition: Filters a collection of input values before the method executes using SpEL.

    Usage: Used to restrict what arguments go into a method.

    Example:

    @PreFilter("filterObject.owner == authentication.name") public void deleteDocuments(List<Document> docs) { // only deletes docs owned by the current user }

    Spring-Specific? Yes


    @PostFilter (less common)

    Definition: Filters the return collection after method execution based on SpEL.

    Usage: Used when you want to return only items a user is allowed to see.

    Example:

    @PostFilter("filterObject.owner == authentication.name") public List<Document> getDocuments() { return documentRepository.findAll(); }

    Spring-Specific? Yes


    @EnableGlobalMethodSecurity

    Definition: Enables method-level security annotations like @Secured, @PreAuthorize, @PostAuthorize.

    Usage: Must be declared in a configuration class to activate those annotations.

    Example:

    @Configuration @EnableGlobalMethodSecurity( securedEnabled = true, prePostEnabled = true, jsr250Enabled = true ) public class MethodSecurityConfig { }

    Spring-Specific? Yes



    9. Spring Validation Annotations


    @Valid

    Definition: Triggers JSR-303 validation on a field, method parameter, or return value.

    Usage: Use in controller method parameters or bean fields to trigger validation automatically.

    Example (in a controller):

    @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User is valid!"); }

    Spring-Specific? No (Standard JSR-303, supported by Spring)


    @Validated

    Definition: Spring-specific annotation that supports validation groups in addition to JSR-303 validation.

    Usage: Used on classes or method parameters to validate beans with group-based rules.

    Example (in a service or controller):

    @Validated @Service public class UserService { public void processUser(@Validated(OnCreate.class) User user) { // validation applies only for the OnCreate group } }

    Spring-Specific? Yes


    @NotNull

    Definition: Validates that the annotated value is not null.

    Usage: Used on fields where null values are not acceptable.

    Example:

    @NotNull(message = "Username must not be null") private String username;

    Spring-Specific? No (JSR-303 standard)


    @NotBlank

    Definition: Validates that the annotated string is not null and is not empty after trimming.

    Usage: Used for validating non-empty text inputs.

    Example:

    @NotBlank(message = "Name is required") private String name;

    Spring-Specific? No (JSR-303 / Hibernate Validator)


    @NotEmpty

    Definition: Validates that a collection, map, or string is not null and not empty.

    Usage: Used for validating lists or strings that must have at least one element or character.

    Example:

    @NotEmpty private List<String> roles;

    Spring-Specific? No


    @Size

    Definition: Validates that the size of a string, collection, or array falls within given bounds.

    Usage: Used to restrict the number of characters or elements.

    Example:

    @Size(min = 6, max = 20) private String password;

    Spring-Specific? No


    @Email

    Definition: Validates that a string is a well-formed email address.

    Usage: Used for email field validation.

    Example:

    @Email private String email;

    Spring-Specific? No (Provided by Hibernate Validator)


    @Min/@Max

    Definition: Validates that a number is greater than (@Min) or less than (@Max) a given value.

    Usage: Used for numerical range constraints.

    Example:

    @Min(18) @Max(99) private int age;

    Spring-Specific? No


    @Pattern

    Definition: Validates that a string matches a given regular expression.

    Usage: Used to enforce format constraints like alphanumeric, phone numbers, etc.

    Example:

    @Pattern(regexp = "^[A-Z][a-z]+$") private String firstName;

    Spring-Specific? No


    @AssertTrue/@AssertFalse

    Definition: Validates that a boolean field is true or false.

    Usage: Used when certain boolean flags must meet a specific value.

    Example:

    @AssertTrue private boolean termsAccepted;

    Spring-Specific? No


    @Past/@Future

    Definition: Validates that a date/time is in the past or future.

    Usage: Used for validating birth dates, expiration dates, etc.

    Example:

    @Past private LocalDate birthDate; @Future private LocalDate subscriptionEndDate;

    Spring-Specific? No


    @Constraint

    Definition: Marks an annotation as a custom validation constraint.

    Usage: Used to create custom validators (e.g., @ValidPhoneNumber, @ValidCurrency).

    Example:

    @Constraint(validatedBy = MyCustomValidator.class) @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface ValidCountry { String message() default "Invalid country"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }

    Spring-Specific? No (JSR-303, but fully usable in Spring)



    10. Spring Conditional & Profile Based Annotations


    @Profile

    Definition: Activates a component only if the specified Spring profile is active.

    Usage: Use this to register beans conditionally based on the environment (e.g., dev, test, prod).

    Example:

    @Profile("dev")
    @Component public class DevDataSourceConfig { @Bean public DataSource dataSource() { return new H2DataSource(); } }

    In application.properties:

    spring.profiles.active=dev

    @Conditional

    Definition: Registers a bean conditionally based on custom logic encapsulated in a Condition class.

    Usage: Use this when complex or custom runtime conditions should decide if a bean should be loaded.

    Example:

    @Configuration public class AppConfig { @Bean @Conditional(MyCondition.class) public MyService myService() { return new MyService(); } }

    Custom condition:

    public class MyCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().containsProperty("app.enabled"); } }

    @ConditionalOnProperty (Spring Boot)

    Definition: Registers a bean only if a specific property is set to a desired value.

    Usage: Use for feature toggles or bean activation via configuration.

    Example:

    @Component @ConditionalOnProperty(name = "feature.sms.enabled", havingValue = "true") public class SmsService { // Loaded only if feature.sms.enabled=true }

    In application.properties:

    feature.sms.enabled=true

    @ConditionalOnMissingBean (Spring Boot)

    Definition: Registers a bean only if the specified bean is not already present in the Spring context.

    Usage: Useful to provide default implementations that can be overridden by user-defined beans.

    Example:

    @Configuration public class DefaultServiceConfig { @Bean @ConditionalOnMissingBean(MyService.class) public MyService defaultMyService() { return new DefaultMyService(); } }

    @ConditionalOnBean (Spring Boot)

    Definition: Registers a bean only if a specified bean already exists in the context.

    Usage: Used for dependent bean creation when another bean must exist.

    Example:

    @Component @ConditionalOnBean(EmailService.class) public class NotificationService { // Loaded only if EmailService is present }

    @ConditionalOnClass (Spring Boot)

    Definition: Registers a bean only if the specified class is available on the classpath.

    Usage: Useful for auto-configuration modules that depend on optional libraries.

    Example:

    @Configuration @ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper") public class JsonConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }

    @ConditionalOnExpression (Spring Boot)

    Definition: Registers a bean conditionally based on a SpEL (Spring Expression Language) expression.

    Usage: Used for flexible configuration using expressions.

    Example:

    @Bean @ConditionalOnExpression("${feature.toggle:true} == true") public FeatureService featureService() { return new FeatureService(); }

    @ActiveProfiles

    Definition: Specifies active Spring profiles when running a test.

    Usage: Used in Spring Boot tests to simulate different runtime environments.

    Example:

    @SpringBootTest @ActiveProfiles("test") public class UserServiceTest { @Autowired UserService userService; }

    @ProfileGroups (Spring Boot 2.4+)

    Definition: Defines logical groupings of Spring profiles that activate multiple profiles under one name.

    Usage: Simplifies environment configuration by grouping related profiles.

    Example (application.yml):

    spring: profiles: group: prod: - prod-db - prod-security

    Then in properties:

    spring.profiles.active=prod

    (All profiles in the group will be activated.)



    11. Spring Configuration Import & Dependencies Annotations


    @Import

    Definition: Imports one or more @Configuration or component classes into another configuration class,

    allowing them to be registered as beans in the application context.

    Usage: Used to modularize and reuse configuration classes without scanning them explicitly.

    Example:

    @Configuration
    @Import({SecurityConfig.class, DataSourceConfig.class})
    public class MainConfig {
    // Main configuration class that includes other configs
    }

    This allows SecurityConfig and DataSourceConfig to be loaded and processed as part of MainConfig.


    @ImportResource

    @Configuration
    @ImportResource("classpath:applicationContext.xml")

    public class AppConfig {
    // Loads beans defined in applicationContext.xml
    }

    Definition: Imports Spring configuration from an external XML file into a Java-based configuration class.

    Usage: Used when you want to combine legacy XML-based Spring configuration with newer Java-based configuration.

    Example:

    This helps during transitional phases where not all configurations are moved to Java classes.


    @DependsOn

    Definition: Indicates that a bean depends on the initialization of one or more other beans.

    Spring ensures the dependent beans are created first.

    Usage: Used when a bean must be initialized only after another bean is fully initialized,

    such as ordering system components or initializing shared resources.

    Example:

    @Component
    @DependsOn("dataSourceInitializer")
    public class UserRepository {
    // This bean is created only after dataSourceInitializer is initialized
    }

    Spring uses this annotation to determine bean creation order during application context initialization.


    @PropertySource

    Definition: Loads property files into the Spring Environment.

    Usage: Used to load .properties files manually when they aren’t located in default locations like application.properties.

    Example:

    @Configuration @PropertySource("classpath:external-config.properties") public class PropertyConfig { }

    This allows values from external-config.properties to be injected via @Value or accessed from the environment.


    @PropertySources

    Definition: Container annotation for defining multiple @PropertySource annotations.

    Usage: Used to load multiple property files in the same configuration class.

    Example:

    @Configuration @PropertySources({ @PropertySource("classpath:db.properties"), @PropertySource("classpath:app.properties") }) public class MultiPropertyConfig { }

    @ConfigurationProperties

    Definition: Binds external configuration properties (from .properties or .yml) to Java beans.

    Usage: Used to map groups of related configuration values to a POJO.

    Example:

    @Component @ConfigurationProperties(prefix = "app") public class AppSettings { private String name; private int timeout; // getters and setters }

    In application.properties:

    app.name=MyApp app.timeout=60

    @ConfigurationPropertiesScan(Spring Boot 2.2+)

    Definition: Scans packages for @ConfigurationProperties classes automatically, eliminating the need for explicit @Component.

    Usage: Used in combination with @SpringBootApplication or @Configuration.

    Example:

    @ConfigurationPropertiesScan("com.example.config") @SpringBootApplication public class MyApplication { }

    @EnableConfigurationProperties

    Definition: Registers @ConfigurationProperties beans without requiring @Component.

    Usage: Used in non-component classes like @Configuration.

    Example:

    @Configuration @EnableConfigurationProperties(AppSettings.class) public class ConfigClass { }

    @ImportRuntimeHints(Spring Native)

    Definition: Provides runtime hints (like reflection or resource access) needed during ahead-of-time (AOT) compilation in Spring Native/GraalVM.

    Usage: Used when running Spring Boot applications as native images.

    Example:

    @ImportRuntimeHints(MyHints.class) @Configuration public class NativeConfig { }

    Where MyHints is a class implementing RuntimeHintsRegistrar.



    12. Bean Lifecycle & Injection Enhancements Annotations


    @PostConstruct

    Definition: Marks a method to be invoked after the bean is constructed and all dependencies have been injected.

    Usage: Use for initialization logic like validating config values, starting background tasks, or setting up connections.

    Example:

    @Component public class CacheLoader { @PostConstruct public void init() { System.out.println("Loading cache after bean creation"); } }

    Spring-Specific? No (Part of JSR-250, but fully supported by Spring)


    @PreDestroy

    Definition: Marks a method to be called before the Spring bean is destroyed.

    Usage: Use for resource cleanup, e.g., closing files, DB connections, or stopping threads.

    Example:

    @Component public class FileWriterBean { @PreDestroy public void closeFile() { System.out.println("File closed during bean destruction"); } }

    Spring-Specific? No (Part of JSR-250, but supported by Spring)


    @Required (deprecated)

    Definition: Marks a bean property as required — Spring will fail to load the application context if it’s not set.

    Usage: Was used to enforce property injection via setter methods. Now deprecated in favor of constructor injection.

    Example:

    @Component public class EmployeeService { @Required public void setRepository(EmployeeRepository repo) { this.repo = repo; } }

    Spring-Specific? Yes (Only exists in Spring; deprecated since Spring 5)


    @Lookup

    Definition: Marks a method to be overridden by Spring to return a new instance of a bean — typically a prototype bean.

    Usage: Use when a singleton bean needs to dynamically access a prototype-scoped bean.

    Example:

    @Component public class ReportManager { @Lookup public ReportGenerator getReportGenerator() { // Spring overrides this method with a proxy return null; } }

    Spring-Specific? Yes (Introduced by Spring)


    @Inject

    Definition: Injects a dependency by type, similar to @Autowired.

    Usage: Used as a standard alternative to @Autowired, especially in Jakarta EE / Javax environments.

    Example:

    @Component public class BillingService { @Inject private PaymentGateway paymentGateway; }

    Spring-Specific? No (Part of JSR-330, but fully supported by Spring)


    @Resource

    Definition: Injects a bean by name (preferred) or by type if name is not found.

    Usage: Use when you want to inject beans by their exact name (legacy or XML-style compatibility).

    Example:

    @Component public class EmailService { @Resource(name = "smtpSender") private MailSender mailSender; }

    Spring-Specific? No (Part of JSR-250, supported by Spring)




    13. Spring Miscellaneous Annotations


    @Order

    Definition: Defines the execution order of components (aspects, filters, interceptors, etc.).

    Usage: Used to control ordering when multiple components of the same type are present.

    Example:

    @Order(1)
    @Component
    public class FirstInterceptor implements HandlerInterceptor { }

    Spring-Specific? Yes


    @ConditionalOnJava

    Definition: Loads a bean only if the application is running on a specified Java version or later.

    Usage: Used in Spring Boot auto-configuration classes.

    Example:

    @Configuration
    @ConditionalOnJava(JavaVersion.EIGHT)
    public class Java8Config {
    }

    Spring-Specific? Yes (Spring Boot)


    @ConditionalOnWebApplication

    Definition: Loads a bean only in a web application context.

    Usage: Used in auto-configuration modules.

    Example:

    @Configuration
    @ConditionalOnWebApplication
    public class WebOnlyConfig {
    }

    Spring-Specific? Yes