<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ziad Sharara on Medium]]></title>
        <description><![CDATA[Stories by Ziad Sharara on Medium]]></description>
        <link>https://medium.com/@ziad-sharara?source=rss-8c9e73dc1ab9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jdNVhq5ub6G26_Y5G3qmdg.jpeg</url>
            <title>Stories by Ziad Sharara on Medium</title>
            <link>https://medium.com/@ziad-sharara?source=rss-8c9e73dc1ab9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:26:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ziad-sharara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[@Component, @Service, @Repository — They’re Not the Same, and One of Them Is Special]]></title>
            <link>https://ziad-sharara.medium.com/component-service-repository-theyre-not-the-same-and-one-of-them-is-special-5adc6bd4e3ce?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5adc6bd4e3ce</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[hibernate-jpa]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 21:26:32 GMT</pubDate>
            <atom:updated>2026-06-18T21:26:32.287Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Honest reason I’m writing this:</em></strong><em> I got asked this in an interview. “What’s the difference between @Component, @Service, and @Repository?” I gave a half-correct answer — said they’re all stereotype annotations that register beans in the Spring context. That part was right. But I missed the most interesting part of the answer. So I went and studied it properly. This article is what I found.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ktzJayEv8H0AkwQ3nq7gMQ.jpeg" /></figure><h3>The Short Answer First</h3><p>All three are “<strong>stereotype annotations”</strong>. All three tell Spring: “hey, create a bean from this class and put it in the Spring context.” When you annotate a class with any of them and have @ComponentScan enabled, Spring picks it up, creates a BeanDefinition for it, and registers a bean.</p><p>That’s the foundation. But it’s not the full story.</p><p>The relationship looks like this:</p><pre>@Component         ← the base annotation<br>    ↑<br>@Service           ← is a @Component (but ONLY semantic)<br>    ↑<br>@Repository        ← is a @Component (but adds REAL behavior)</pre><p>@Service and @Repository are both meta-annotated with @Component. So technically, they ARE @Component. The difference is what each one adds on top.</p><h3>@Component : The Base</h3><p>@Component is the generic, catch-all stereotype. No special behavior. No extra features. It just says &quot;this class is a Spring-managed component.&quot;</p><pre>@Component<br>public class EmailValidator {<br><br>    public boolean isValid(String email) {<br>        return email != null &amp;&amp; email.contains(&quot;@&quot;);<br>    }<br><br>}</pre><p>When would you actually use plain @Component? When your class doesn&#39;t clearly belong to a layer. A utility class, a helper, a general-purpose tool.</p><p>If it&#39;s infrastructure and not clearly a service or repository, @Component is the right choice.</p><h3>@Service : A @Component with a Name Tag</h3><p>@Service is just @Component with a different name. That&#39;s it. Technically, they behave identically. Spring treats them the same way. No extra behavior, no additional BeanPostProcessor, nothing special happens at runtime.</p><p>So why does it exist?</p><p><strong>Intent and readability.</strong> When a developer sees @Service, they know: &quot;this class lives in the business logic layer, it implements use cases, it doesn&#39;t talk to the database directly.&quot; When they see @Component, they know: &quot;this is something generic.&quot;</p><pre>@Service<br>public class PaymentService {<br><br>    private final PaymentRepository paymentRepository;<br><br>    public PaymentService(PaymentRepository paymentRepository) {<br>        this.paymentRepository = paymentRepository;<br>    }<br><br>    public void processPayment(Payment payment) {<br>        // business logic here<br>        paymentRepository.save(payment);<br>    }<br><br>}</pre><p>There’s also a future-proofing argument: Spring or other frameworks in your project might decide to add special behavior for @Service beans later (like automatic transaction demarcation). Using the right annotation from the start means you&#39;re already in the right place if that happens.</p><p>But right now, @Service vs @Component on a service-layer class? <strong>Zero technical difference.</strong> The difference is entirely semantic.</p><h3>@Repository : This One Is Actually Special</h3><p>Here’s where it gets interesting. And here’s what I missed in my interview.</p><p>@Repository doesn&#39;t just register a bean. It “<strong>enables exception translation”</strong>.</p><p>Let me explain what that means, because it’s the most important thing in this article.</p><h3>The Problem: Leaky Persistence Exceptions</h3><p>When something goes wrong in your database layer; duplicate key, constraint violation, entity not found — the persistence framework you’re using throws its own specific exception.</p><p>Hibernate throws HibernateException or ConstraintViolationException. JDBC throws SQLException. Each framework has its own exception hierarchy.</p><p>If you just use @Component on your repository class, those exceptions propagate up exactly as they are. Now your service layer has to catch Hibernate-specific exceptions:</p><pre>// Bad — service layer now knows about Hibernate<br>@Service<br>public class UserService {<br><br>    public void createUser(User user) {<br>        try {<br>            userRepository.save(user);<br>        } catch (org.hibernate.exception.ConstraintViolationException e) {<br>            // Your service now has a Hibernate import. That&#39;s a problem.<br>        }<br>    }<br><br>}</pre><p>This is called “<strong>leaky abstraction”</strong>. Your service layer is supposed to be “database-agnostic”. It shouldn’t care whether you’re using Hibernate, JDBC, JPA, or MongoDB underneath. But now it does — because it’s catching Hibernate exceptions directly.</p><h3>The Fix: @Repository + Exception Translation</h3><p>When Spring sees @Repository on a class, it activates a BeanPostProcessor called PersistenceExceptionTranslationPostProcessor. If you&#39;ve read <a href="https://ziad-sharara.medium.com/i-finally-understood-what-spring-does-at-startup-4749b9bd9245">Article #2</a> about the Spring lifecycle, you already know what a BeanPostProcessor is — it&#39;s a hook that runs after the bean is created and can wrap it in a proxy.</p><p>That’s exactly what happens. Spring wraps your @Repository bean in a proxy. That proxy intercepts every method call and catches any persistence-specific exception that comes out. Then it <strong>translates</strong> it into Spring&#39;s own exception hierarchy — DataAccessException.</p><pre>WITHOUT @Repository:<br>DAO method → throws HibernateException → propagates up raw → service catches Hibernate exception<br><br>WITH @Repository:<br>DAO method → throws HibernateException → PROXY intercepts it → translates → throws DataAccessException → service catches Spring exception</pre><p>Now your service layer can catch DataAccessException — Spring&#39;s own abstraction — without ever knowing which persistence framework is running underneath:</p><pre>// Clean — service layer is database-agnostic<br>@Service<br>public class UserService {<br><br>    public void createUser(User user) {<br>        try {<br>            userRepository.save(user);<br>        } catch (DataIntegrityViolationException e) {<br>            // Spring&#39;s exception — no Hibernate import needed<br>            throw new UserAlreadyExistsException(&quot;Email already registered&quot;);<br>        }<br>    }<br><br>}</pre><p>Tomorrow you could swap Hibernate for something else entirely, and your service code doesn’t change at all.</p><h3>Spring’s DataAccessException hierarchy</h3><p>Some common subtypes you’ll encounter:</p><pre>DataAccessException<br>├── DataIntegrityViolationException   — unique key, foreign key, NOT NULL violation<br>├── EmptyResultDataAccessException    — expected a result, got nothing<br>├── DuplicateKeyException             — duplicate primary/unique key<br>├── DeadlockLoserDataAccessException  — lost in a database deadlock<br>└── QueryTimeoutException             — query took too long</pre><p>Meaningful, readable, framework-agnostic. That’s what @Repository gives you.</p><h3>Behind the Scenes — How Spring Finds All Three</h3><p>When Spring does a component scan, it uses ClassPathBeanDefinitionScanner to walk through your packages. It&#39;s looking for classes annotated with @Component — but because @Service and @Repository are themselves meta-annotated with @Component, the scanner picks them all up.</p><p>Here’s what @Repository actually looks like internally in Spring&#39;s source:</p><pre>@Target(ElementType.TYPE)<br>@Retention(RetentionPolicy.RUNTIME)<br>@Documented<br>@Component        // ← it IS a @Component<br>public @interface Repository {<br>    String value() default &quot;&quot;;<br>}</pre><p>Same for @Service:</p><pre>@Target(ElementType.TYPE)<br>@Retention(RetentionPolicy.RUNTIME)<br>@Documented<br>@Component        // ← also IS a @Component<br>public @interface Service {<br>    String value() default &quot;&quot;;<br>}</pre><p>So when the scanner finds a class annotated with @Repository, it sees @Component in the meta-annotations and registers the bean. Then separately, PersistenceExceptionTranslationPostProcessor runs during the BeanPostProcessor phase of the lifecycle and says: &quot;is this bean annotated with @Repository? If yes, wrap it in a translation proxy.&quot;</p><p>One annotation, two things happening. That’s the part most explanations skip.</p><h3>Where to Put Each One — The Practical Guide</h3><pre>┌────────────────────────────────────────────────────────┐<br>│  Presentation Layer  →  @Controller / @RestController  │<br>├────────────────────────────────────────────────────────┤<br>│  Business Logic      →  @Service                       │<br>├────────────────────────────────────────────────────────┤<br>│  Data Access         →  @Repository                    │<br>├────────────────────────────────────────────────────────┤<br>│  Generic/Utility     →  @Component                     │<br>└────────────────────────────────────────────────────────┘</pre><p>A few questions to decide which one to use:</p><p>Does the class talk to the database? → @Repository</p><p>Does the class implement business use cases? → @Service</p><p>Does the class handle HTTP requests? → @Controller / @RestController</p><p>Does the class not fit any of the above? → @Component</p><h3>Wait — What About Spring Data JPA Interfaces?</h3><p>Good question. If you use Spring Data JPA, you probably write things like:</p><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p>You didn’t annotate it with anything. So how does exception translation work?</p><p>Spring Data JPA applies @Repository semantics automatically to all repository interfaces it manages. So you get exception translation without writing the annotation yourself. But if you&#39;re writing a custom repository class (not an interface), you need @Repository explicitly.</p><h3>Full Example — All Three Working Together</h3><p>Here’s a minimal but complete example showing the right annotation at the right layer:</p><pre>// Data Access Layer<br>@Repository<br>public class ProductRepository {<br><br>    @PersistenceContext<br>    private EntityManager entityManager;<br><br>    public Product findById(Long id) {<br>        Product product = entityManager.find(Product.class, id);<br>        if (product == null) {<br>            throw new EmptyResultDataAccessException(1); // Spring&#39;s own exception<br>        }<br>        return product;<br>    }<br><br>    public void save(Product product) {<br>        entityManager.persist(product);<br>        // if this throws a Hibernate exception,<br>        // @Repository proxy translates it to DataAccessException<br>    }<br><br>}<br><br>// Business Logic Layer<br>@Service<br>public class ProductService {<br><br>    private final ProductRepository productRepository;<br><br>    public ProductService(ProductRepository productRepository) {<br>        this.productRepository = productRepository;<br>    }<br><br>    public Product getProduct(Long id) {<br>        try {<br>            return productRepository.findById(id);<br>        } catch (EmptyResultDataAccessException e) {<br>            // Spring&#39;s exception — no Hibernate dependency here<br>            throw new ProductNotFoundException(&quot;Product &quot; + id + &quot; not found&quot;);<br>        }<br>    }<br><br>}<br><br>// Generic Utility<br>@Component<br>public class PriceFormatter {<br>    public String format(double price) {<br>        return String.format(&quot;%.2f EGP&quot;, price);<br>    }<br>}</pre><p>Each class is in the right layer with the right annotation. The ProductRepository gets exception translation for free. The ProductService catches Spring&#39;s DataAccessException without knowing anything about Hibernate. The PriceFormatter is just a utility — @Component is the honest choice.</p><h3>The Interview Answer — Clean Version</h3><p>So if someone asks you “what’s the difference between @Component, @Service, and @Repository?”, here’s the complete answer:</p><p>All three are stereotype annotations that register beans in the Spring context and are picked up by component scanning. @Service and @Repository are both meta-annotated with @Component, so they inherit that behavior.</p><p>The difference:</p><p>@Component vs @Service — <strong>purely semantic</strong>. No technical difference. @Service signals &quot;this is a business logic bean.&quot; Same behavior.</p><p>@Component vs @Repository — <strong>there is a real technical difference</strong>. @Repository activates exception translation through PersistenceExceptionTranslationPostProcessor. This is a BeanPostProcessor that wraps your DAO in a proxy, intercepts persistence-specific exceptions (Hibernate, JDBC), and translates them into Spring&#39;s unified DataAccessException hierarchy. Without @Repository, vendor-specific exceptions leak into your service layer.</p><p>That’s the answer most people stop before they get to.</p><p><em>As always — if I got something wrong or missed something, let me know in the comments. Still learning, still documenting.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5adc6bd4e3ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finally Understood Spring #3: AOP, Proxies, and the Magic Behind @Transactional]]></title>
            <link>https://ziad-sharara.medium.com/i-finally-understood-spring-3-aop-proxies-and-the-magic-behind-transactional-5182304ba60c?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5182304ba60c</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[aspect-oriented]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 14:57:35 GMT</pubDate>
            <atom:updated>2026-06-09T14:57:35.860Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>If you’ve been following this series:</em></strong><em> In </em><a href="https://ziad-sharara.medium.com/i-finally-understood-what-spring-does-at-startup-4749b9bd9245"><em>article #2</em></a><em>, I wrote about the Spring lifecycle and mentioned that BeanPostProcessors can wrap your beans in proxy objects. I said “this is a teaser for AOP” and kept moving. This is that article. And honestly, understanding the lifecycle first made AOP click </em>much<em> faster — so if you haven’t read that one, it might be worth a quick look before continuing here.</em></blockquote><blockquote><strong><em>If this is your first article from me:</em></strong><em> I’m a software engineer documenting everything I learn on my backend journey. This is based on Chapter 6 of </em>Spring Start Here<em> by Laurentiu Spilca. Let’s get into it.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*mYO9Hkw2sMZGsvF586UWsQ.jpeg" /></figure><h3>The Problem AOP Is Solving</h3><p>Before touching any code, let me convince you why AOP exists at all. Because if you start with “here’s how to create an aspect” without understanding the “why”, it’s going to feel like an over-complicated solution to a problem you’ve never had.</p><p>Imagine you have a service with a few use cases:</p><pre>@Service<br>public class OrderService {<br><br>   public void placeOrder(Order order) {<br>        // actual business logic<br>    }<br><br>   public void cancelOrder(Long orderId) {<br>        // actual business logic<br>    }<br><br>   public void trackOrder(Long orderId) {<br>        // actual business logic<br>    }<br><br>}</pre><p>Now your team gets a requirement: log the start and end time of every method execution. Simple enough. You add it:</p><pre>public void placeOrder(Order order) {<br><br>    logger.info(&quot;placeOrder started at: &quot; + LocalDateTime.now());<br><br>    // business logic<br><br>    logger.info(&quot;placeOrder ended at: &quot; + LocalDateTime.now());<br><br>}</pre><p>Then you repeat this for cancelOrder, trackOrder, and every other method. Now a new requirement: every method needs a security check. You add that too, everywhere. Then transaction handling. Then input validation.</p><p>Suddenly every method is 80% infrastructure boilerplate and 20% actual business logic. You want to read placeOrder and understand what it does, but you have to scroll past a wall of logging and security checks to find the relevant code.</p><p>This is what AOP is for. It lets you <strong>pull that infrastructure code out completely</strong>, put it in one place, and have Spring weave it back in transparently, without the method knowing it’s being “intercepted”.</p><h3>The Terminology (I’ll Keep This Short)</h3><p>When I first read about AOP, the terminology genuinely confused me. Let me map it out once cleanly:</p><p><strong>“Aspect”:</strong> the class containing the logic you want to apply to other methods (e.g., the logging class)</p><p><strong>“Advice</strong> “: <em>when</em> the aspect logic runs relative to the intercepted method (before? after? instead of? both?)</p><p><strong>“Pointcut”:</strong> <em>which</em> methods to intercept (defined by an expression)</p><p><strong>“Join Point”: </strong>the event that triggers the aspect. In Spring, this is <em>always</em> a method call. Nothing else.</p><p><strong>“Target Object”:</strong> the bean whose method is being intercepted</p><p><strong>“Weaving”:</strong> the process of Spring connecting the aspect to the target object</p><p>That’s it. Five terms. Once I had these mapped, the rest made sense.</p><h3>The Proxy Connection (The Part That Actually Made It Click)</h3><p>Here’s the thing I kept wondering when I first used @Autowired: why does Spring give me the bean I asked for? Like, what actually happens when I write:</p><pre>@Autowired<br>private OrderService orderService;</pre><p>Back in <a href="https://medium.com/r?url=https%3A%2F%2Fziad-sharara.medium.com%2Fi-finally-understood-what-spring-does-at-startup-4749b9bd9245">Article #2</a>, I explained that when you define an aspect for a bean, Spring doesn’t give you a reference to the real bean. It gives you a <strong>proxy object: </strong>a dynamically generated wrapper that intercepts your method calls, runs the aspect logic, and then (optionally) delegates to the real method.</p><p>This is the “aha” for me. AOP isn’t magic, it’s Spring’s BeanPostProcessor at work. During the startup lifecycle, after your bean is created and initialized, a BeanPostProcessor (specifically AnnotationAwareAspectJAutoProxyCreator) checks: &quot;does this bean have any aspects defined for it?&quot; If yes, it replaces the bean in the context with a proxy.</p><p>So when you call orderService.placeOrder(order), you&#39;re not calling OrderService.placeOrder() directly. You&#39;re calling the proxy&#39;s version, which runs the aspect, then calls the real method.</p><pre>You → Proxy → Aspect Logic → Real Method → Back to Proxy → Back to You</pre><p>This is weaving. And it happens invisibly.</p><h3>Building an Aspect: The 4 Steps</h3><p>Okay, let’s actually write one. The book walks through four steps, and they’re clean enough that I’ll follow the same structure.</p><h3>Step 1: Enable AOP in your configuration</h3><p>Spring doesn’t enable AOP by default. You have to turn it on:</p><pre>@Configuration<br>@ComponentScan(basePackages = &quot;services&quot;)<br>@EnableAspectJAutoProxy       // ← this is what activates the AOP machinery<br>public class AppConfig {<br>}</pre><p>One annotation. Done.</p><h3>Step 2: Create the aspect class and add it as a bean</h3><pre>@Aspect<br>@Component         // ← don&#39;t forget this part<br>public class LoggingAspect {<br>    // logic coming soon<br>}</pre><p>Here’s a gotcha the book explicitly warns about: <strong>@Aspect is NOT a stereotype annotation.</strong> It tells Spring &quot;this class defines aspect logic&quot; but it does <em>not</em> automatically create a bean. If you forget @Component (or add it via @Bean in your config), the aspect silently does nothing. No error, no warning. Just no interception.</p><h3>Step 3: Define the advice and pointcut</h3><p>This is where you tell Spring <em>when</em> to intercept and <em>which</em> methods to intercept:</p><pre>@Aspect<br>@Component<br>public class LoggingAspect {<br><br>    @Around(&quot;execution(* services.*.*(..))&quot;)<br>    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {<br><br>        // logic here<br><br>        return joinPoint.proceed();<br>    }<br>}</pre><p>Two things here:</p><p><strong>The </strong><strong>@Around annotation</strong> is the “advice”; it means &quot;run this logic <em>around</em> the intercepted method&quot; (before and after). It&#39;s the most flexible of the advice types and the one you&#39;ll use most.</p><p><strong>The string expression</strong> &quot;execution(* services.*.*(..))&quot; is an <strong>AspectJ pointcut expression</strong>.</p><pre>execution(* services.*.*(..))<br>           │   │     │  │<br>           │   │     │  └── any parameters<br>           │   │     └── any method name<br>           │   └── any class in the services package<br>           └── any return type</pre><p>It means: intercept every method in every class inside the services package, regardless of return type, method name, or parameters. That&#39;s it.</p><p>In practice, you won’t write these from scratch. You reference the docs or use the annotation-based approach.</p><h3>Step 4: Implement the logic</h3><pre>@Aspect<br>@Component<br>public class LoggingAspect {<br>    private Logger logger = Logger.getLogger(LoggingAspect.class.getName());<br><br>    @Around(&quot;execution(* services.*.*(..))&quot;)<br>    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {<br><br>        logger.info(&quot;Method will execute&quot;);<br>        Object returnedValue = joinPoint.proceed();   // calls the real method<br>        logger.info(&quot;Method executed and returned: &quot; + returnedValue);<br><br>        return returnedValue;<br>    }<br>}</pre><p>joinPoint.proceed() is the key line. It&#39;s what delegates to the actual method. If you don&#39;t call it, the real method never runs. The caller won&#39;t know.</p><h3>ProceedingJoinPoint: More Than Just proceed()</h3><p>The ProceedingJoinPoint parameter is your window into the intercepted method. You can pull out useful information without the method having to pass it to you explicitly:</p><pre>String methodName = joinPoint.getSignature().getName();  // &quot;placeOrder&quot;<br>Object[] args = joinPoint.getArgs();         // the actual arguments passed</pre><p>So an aspect that logs the method name and its parameters:</p><pre>@Around(&quot;execution(* services.*.*(..))&quot;)<br>public Object log(ProceedingJoinPoint joinPoint) throws Throwable {<br><br>    String name = joinPoint.getSignature().getName();<br>    Object[] args = joinPoint.getArgs();<br><br>    logger.info(&quot;&gt;&gt; &quot; + name + &quot; called with: &quot; + Arrays.asList(args));<br>    Object result = joinPoint.proceed();<br>    logger.info(&quot;&lt;&lt; &quot; + name + &quot; returned: &quot; + result);<br><br>    return result;<br>}</pre><p>And since you control what happens before and after proceed(), you can also modify the arguments going in or the return value coming out. Which... be careful with. The book specifically warns about this, and I agree ; changing method arguments through an aspect is the kind of thing that makes a codebase very hard to debug.</p><h3>The Better Approach: Custom Annotations</h3><p>Package-wide pointcut expressions like execution(* services.*.*(..)) intercept <em>every</em> method in that package. Which is rarely what you want.</p><p>A cleaner approach; is using a <strong>custom annotation</strong> to mark exactly which methods you want intercepted.</p><p>First, define the annotation:</p><pre>@Retention(RetentionPolicy.RUNTIME)   // ← MUST be RUNTIME, not default<br>@Target(ElementType.METHOD)<br>public @interface ToLog {<br>}</pre><p>The @Retention(RetentionPolicy.RUNTIME) is critical. By default in Java, annotations are not available at “runtime”, they&#39;re “compile-time” metadata. You have to explicitly tell the JVM to keep this annotation around at runtime so Spring can read it.</p><p>Now mark the methods you want intercepted:</p><pre>@Service<br>public class CommentService {<br>    public void publishComment(Comment comment) {<br>        // NOT intercepted — no annotation<br>    }<br>    @ToLog   // ← only this one gets intercepted<br>    public void deleteComment(Comment comment) {<br>        // intercepted<br>    }<br>    public void editComment(Comment comment) {<br>        // NOT intercepted — no annotation<br>    }<br>}</pre><p>And update the aspect’s pointcut expression:</p><pre>@Around(&quot;@annotation(ToLog)&quot;)<br>public Object log(ProceedingJoinPoint joinPoint) throws Throwable {<br>    // same logic as before<br>}</pre><p>@annotation(ToLog) : intercept any method annotated with @ToLog.</p><h3>Other Advice Annotations</h3><p>@Around is the most powerful but also the most &quot;you need to handle everything yourself.&quot; For simpler cases, Spring offers four alternatives that are more declarative about their intent:</p><pre>@Before         → runs before the method, always<br>@After          → runs after, whether it succeeded or threw an exception<br>@AfterReturning → runs after, only on successful return (gives you the return value)<br>@AfterThrowing  → runs after, only when an exception was thrown (gives you the exception)</pre><p>The difference from @Around: these don&#39;t get a ProceedingJoinPoint. They can&#39;t decide whether to call the real method or not, that decision is baked into the annotation&#39;s semantics. Which is exactly why you&#39;d use them for simple cases. Less flexibility, less rope to hang yourself with.</p><p>Quick example of @AfterReturning:</p><pre>@AfterReturning(value = &quot;@annotation(ToLog)&quot;, returning = &quot;returnedValue&quot;)<br>public void log(Object returnedValue) {<br>    logger.info(&quot;Method returned: &quot; + returnedValue);<br>}</pre><p>Clean and explicit about what it does.</p><h3>When Multiple Aspects Intercept the Same Method</h3><p>This one got me. What happens when two aspects both want to intercept the same method?</p><p>Spring chains them. It’s like a nested wrapper,</p><p>Aspect A wraps Aspect B, which wraps the real method.</p><p>When Aspect A calls proceed(), it doesn&#39;t go straight to the real method,</p><p>it goes to Aspect B.</p><p>When Aspect B calls proceed(), <em>then</em> it hits the real method.</p><pre>Caller → Aspect A → Aspect B → Real Method → Aspect B → Aspect A → Caller</pre><p>The order matters. Imagine you have a SecurityAspect that sometimes blocks the call (doesn&#39;t call proceed()) and a LoggingAspect that logs every execution. If SecurityAspect runs first and blocks the call, LoggingAspect never fires. If you need to log even the blocked calls, LoggingAspect needs to run first.</p><p>By default, Spring doesn’t guarantee execution order for aspects in the same chain. To set it explicitly, use @Order:</p><pre>@Aspect<br>@Component<br>@Order(1)           // runs first<br>public class SecurityAspect { ... }<br><br>@Aspect<br>@Component<br>@Order(2)           // runs second<br>public class LoggingAspect { ... }</pre><p>Lower number = runs first (outermost wrapper).</p><p>Higher number = runs later (closer to the real method).</p><h3>When NOT to Use Aspects</h3><p>The book dedicates a few paragraphs to this and I think it’s worth repeating, because “aspects can do anything” is the kind of statement that leads to unmaintainable code.</p><p>The rule I took from this chapter: use aspects only for <strong>cross-cutting concerns; </strong>things that apply broadly across your app and are not specific to the business logic of any one method. Classic examples:</p><ul><li>Logging and monitoring</li><li>Security checks</li><li>Transaction management</li><li>Performance measurement</li></ul><p>What you want to avoid: using aspects to hide business logic, modify parameters in non-obvious ways, or implement behavior that a developer reading the method signature would have no reason to suspect exists. The golden test; <em>if someone removes the aspect, does the core feature still work correctly?</em> If yes, the aspect is infrastructure. If no, the logic belongs in the method.</p><p>Also: if you find yourself writing complex AspectJ pointcut expressions to target very specific methods, stop and ask if a simpler approach exists. Complex expressions are hard to read, hard to test, and break in non-obvious ways when you refactor.</p><h3>What This Unlocks</h3><p>Here’s the thing that made me actually care about this chapter: <strong>Spring itself is built on AOP</strong>.</p><p>@Transactional? An aspect. When Spring sees that annotation on a method, it wraps the bean in a proxy. Before calling the real method, the proxy opens a transaction. After the method returns, it commits. If an exception is thrown, it rolls back. All of that is an aspect running around your method, and you&#39;ve been using it without knowing the mechanism.</p><p>Spring Security’s method-level security (@PreAuthorize, @Secured)? Also an aspect. The security check runs before your method. If the check fails, proceed() is never called.</p><p>Understanding AOP doesn’t just help me write my own aspects. It helps me understand <em>why</em> @Transactional has the quirks it does (like not working on private methods or when called from within the same class, both are proxy limitations). It helps you debug Spring Security issues. It gives you a mental model for a huge part of the framework&#39;s behavior.</p><h3>Full Working Example</h3><p>Here’s a clean, minimal example putting everything together using the custom annotation approach:</p><pre>// 1. The custom annotation<br>@Retention(RetentionPolicy.RUNTIME)<br>@Target(ElementType.METHOD)<br>public @interface Monitored {<br>}<br><br>// 2. The service (target object)<br>@Service<br>public class PaymentService {<br><br>    public void processPayment(Payment payment) {<br>        System.out.println(&quot;Processing: &quot; + payment.getAmount());<br>    }<br><br>    @Monitored<br>    public String confirmPayment(Long paymentId) {<br>        System.out.println(&quot;Confirming payment: &quot; + paymentId);<br>        return &quot;CONFIRMED&quot;;<br>    }<br><br>}<br><br>// 3. The aspect<br>@Aspect<br>@Component<br>public class MonitoringAspect {<br><br>    private Logger logger = Logger.getLogger(MonitoringAspect.class.getName());<br><br>    @Around(&quot;@annotation(Monitored)&quot;)<br>    public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable {<br><br>        String method = joinPoint.getSignature().getName();<br>        Object[] args = joinPoint.getArgs();<br>        long start = System.currentTimeMillis();<br><br>        logger.info(&quot;&gt;&gt; &quot; + method + &quot; | args: &quot; + Arrays.asList(args));<br><br>        Object result = joinPoint.proceed();<br>        long duration = System.currentTimeMillis() - start;<br>        logger.info(&quot;&lt;&lt; &quot; + method + &quot; | returned: &quot; + result + &quot; | took: &quot; + duration + &quot;ms&quot;);<br><br>        return result;<br>    }<br>}<br><br>// 4. The configuration<br>@Configuration<br>@ComponentScan(basePackages = {&quot;services&quot;, &quot;aspects&quot;})<br>@EnableAspectJAutoProxy<br>public class AppConfig {<br>}</pre><p>Only confirmPayment gets monitored. processPayment runs untouched. The business logic in both methods is clean, no logging, no timing code cluttering the actual logic.</p><h3>What I’m Taking From This Chapter</h3><p>AOP was one of those concepts I’d heard about but never really understood what problem it was solving. After reading Chapter 6, two things stuck:</p><p>First: the proxy connection. Every time I used @Transactional or @PreAuthorize, I was using an aspect without knowing it. Understanding that these are just BeanPostProcessors wrapping my beans in proxies changes how I read Spring stack traces and debug weird behaviors.</p><p>Second: the discipline. The chapter keeps warning about overusing aspects, and I think that’s the most important takeaway. Aspects are good at hiding things. The only things worth hiding are things that would be noise if they were visible. The moment you use an aspect to hide something that <em>matters</em> to understanding the code, you’ve made your app harder to work on.</p><h3><em>Reference: Spring Start Here by Laurentiu Spilca (Manning), Chapter 6.</em></h3><p><em>As always — if something here is wrong or incomplete, tell me in the comments. I’m learning out loud.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5182304ba60c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hibernate Told Me There Was a Gap — Turns Out, I Was the Gap]]></title>
            <link>https://ziad-sharara.medium.com/hibernate-told-me-there-was-a-gap-turns-out-i-was-the-gap-0a84343e6213?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a84343e6213</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[hibernate-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 15:31:19 GMT</pubDate>
            <atom:updated>2026-06-07T15:31:19.611Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>This one’s different.</em></strong><em> The other articles in this series come from studying books and courses. This one comes from work. I was debugging a real Spring Boot API, hitting a real error, and didn’t understand what was happening or why the fix worked. I fixed it with Gemini’s help, then went back and made myself understand every line. This is what I found.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iy42NdEbBuruzJE8FnHOMQ.png" /></figure><h3>The Error</h3><p>The endpoint was a search API for garden requests. POST request, filters sent in the body — text search, project codes, status IDs. Simple enough on the surface.</p><p>Until I ran it and got this:</p><pre>org.hibernate.QueryException: Unexpected gap in ordinal parameter labels [1 -&gt; 3] : [1,3,4,5,6,7,8]</pre><p>“Unexpected gap in ordinal parameter labels.” I had no idea what that meant. The query was running, the app was booting fine, but the moment I hit that endpoint — crash.</p><p>Let me show you what my repository method looked like.</p><h3>The Query That Caused It</h3><pre>@Query(&quot;SELECT r FROM RequestDetails r &quot; +<br>       &quot;WHERE (r.name LIKE CONCAT(&#39;%&#39;, ?1, &#39;%&#39;) OR r.id = ?1) &quot; +<br>       &quot;AND r.project IN ?2 AND r.requestStatusId IN ?3 &quot; +<br>       &quot;AND r.requestTypeId = ?4 &quot; +<br>       &quot;ORDER BY r.requestCreationTime DESC&quot;)<br>Page&lt;RequestDetails&gt; searchWithAll(<br>        String name,<br>        List&lt;String&gt; projects,<br>        List&lt;Integer&gt; statusIds,<br>        Integer requestTypeId,<br>        Pageable page<br>);</pre><p>At first glance this looks fine. Four parameters, numbered ?1 through ?4 in order. The types match the method signature. Nothing obviously wrong.</p><p>But there are actually two bugs hiding here. One causes the crash. One is a silent logic mistake that would have caused a different crash later.</p><h3>Bug #1 — The Crash: Using ?1 Twice</h3><p>Look at the WHERE clause:</p><pre>&quot;WHERE (r.name LIKE CONCAT(&#39;%&#39;, ?1, &#39;%&#39;) OR r.id = ?1) &quot;</pre><p>I used ?1 twice. Once for the LIKE search, and again for the ID comparison. Seemed fine to me — it&#39;s the same parameter, I just want to search both fields with it.</p><p>But here’s what Hibernate 5 actually does when it parses a @Query.</p><p><strong>How Hibernate reads positional parameters:</strong></p><p>When Spring starts up and loads your repository, Hibernate reads the query string and builds an internal list of every ? placeholder it finds, in the order they appear. It then maps these to the Java method parameters by number.</p><p>When it sees ?1 appear twice, its internal counter gets confused. It has to account for both occurrences. So its internal list starts looking something like [1, 1, 2, ...].</p><p>Now here’s where the second layer of the problem kicks in.</p><p><strong>How Spring Data JPA handles IN clauses:</strong></p><p>My requestStatusId list had 5 values. Spring Data JPA doesn&#39;t send a list as a single parameter — it expands IN ?3 into individual slots. So IN ?3 with 5 status IDs becomes IN (?3, ?4, ?5, ?6, ?7) internally.</p><p>By the time Hibernate finishes parsing the whole thing, the internal slot list looks like:</p><pre>[1, 3, 4, 5, 6, 7, 8]</pre><p>See the jump? 1 → 3. Position 2 is missing. Hibernate expects parameters to be numbered sequentially with no gaps — and it explodes:</p><pre>Unexpected gap in ordinal parameter labels [1 -&gt; 3] : [1,3,4,5,6,7,8]</pre><p>The error message is actually telling you exactly what happened. I just didn’t know how to read it at the time.</p><h3>Bug #2 — The Silent One: Strict Typing</h3><p>Even if the first bug hadn’t crashed the app, this would have:</p><pre>&quot;OR r.id = ?1&quot;</pre><p>r.id is an Integer. ?1 comes from String name.</p><p>If someone types &quot;Garden&quot; into the search box, this condition becomes r.id = &#39;Garden&#39;. In Java and SQL, you can&#39;t compare a number column to a string. No automatic conversion, no silent coercion. It throws a type mismatch error.</p><p>If you’re coming from JavaScript, this trips people up a lot. In JS, 1 == &#39;1&#39; is true because JavaScript does automatic type coercion. Java and SQL databases do not. They&#39;re strictly typed, and comparing an Integer to a String is a compiler or runtime error waiting to happen.</p><h3>The Fix: Named Parameters</h3><p>Both bugs go away when you switch from positional parameters (?1, ?2) to named parameters (:name, :projects).</p><p>Here’s the fixed query:</p><pre>@Query(&quot;SELECT r FROM RequestDetails r &quot; +<br>       &quot;WHERE (r.name LIKE CONCAT(&#39;%&#39;, :name, &#39;%&#39;) OR CAST(r.id AS string) = :name) &quot; +<br>       &quot;AND r.project IN :projects &quot; +<br>       &quot;AND r.requestStatusId IN :statusIds &quot; +<br>       &quot;AND r.requestTypeId = :requestTypeId &quot; +<br>       &quot;ORDER BY r.requestCreationTime DESC&quot;)<br>Page&lt;RequestDetails&gt; searchWithAll(<br>        @Param(&quot;name&quot;) String name,<br>        @Param(&quot;projects&quot;) List&lt;String&gt; projects,<br>        @Param(&quot;statusIds&quot;) List&lt;Integer&gt; statusIds,<br>        @Param(&quot;requestTypeId&quot;) Integer requestTypeId,<br>        Pageable page<br>);</pre><p><strong>Why this fixes Bug #1:</strong></p><p>Named parameters are matched by label, not by counting positions. Hibernate doesn’t build a sequential list and count gaps — it just looks up :name and maps it to whatever you annotated @Param(&quot;name&quot;). You can use :name ten times in the same query and Hibernate doesn&#39;t care. No counting, no gaps, no crash.</p><p><strong>Why this fixes Bug #2:</strong></p><p>CAST(r.id AS string) converts the numeric ID to text before comparing it to the search input. So now both sides of the = are strings. If someone types &quot;Garden&quot;, the database compares &quot;1&quot; to &quot;Garden&quot; — safely returns false, no crash.</p><h3>The Rule I’m Taking From This</h3><p>Positional parameters (?1, ?2, ?3) in Spring Data JPA @Query are fragile by design. They break if you:</p><ul><li>Use the same parameter more than once</li><li>Have a list parameter that Spring expands into multiple slots</li><li>Reorder the method parameters later and forget to renumber the query</li></ul><p>Named parameters don’t have any of these problems. Hibernate matches by name, not by position. The method parameters can be in any order, you can reuse them, and adding a new parameter won’t renumber everything else.</p><p>There’s no good reason to use positional parameters in a @Query. Just use named ones.</p><h3>One More Thing I Noticed in the Logs</h3><p>While debugging, I saw this in the Spring Boot startup logs:</p><pre>WARN: HHH000174: Function template anticipated 4 arguments, but 1 arguments encountered</pre><p>This was Hibernate warning that something was off with the query structure — but it’s a WARN, not an ERROR, so the app still booted. The crash only happened at runtime when the endpoint was actually called.</p><p>This is a good reminder: <strong>startup success doesn’t mean your queries are correct.</strong> Spring Data JPA validates and loads @Query strings lazily, not eagerly at boot. The error only surfaces when that specific repository method gets executed. So always test your search endpoints — don&#39;t assume because the app starts, everything is fine.</p><h3>Full Comparison: Before vs After</h3><p><strong>Before (broken):</strong></p><pre>@Query(&quot;SELECT r FROM RequestDetails r &quot; +<br>       &quot;WHERE (r.name LIKE CONCAT(&#39;%&#39;, ?1, &#39;%&#39;) OR r.id = ?1) &quot; +<br>       &quot;AND r.project IN ?2 AND r.requestStatusId IN ?3 &quot; +<br>       &quot;AND r.requestTypeId = ?4 &quot; +<br>       &quot;ORDER BY r.requestCreationTime DESC&quot;)<br>Page&lt;RequestDetails&gt; searchWithAll(<br>        String name,<br>        List&lt;String&gt; projects,<br>        List&lt;Integer&gt; statusIds,<br>        Integer requestTypeId,<br>        Pageable page<br>);</pre><p>Problems: ?1 used twice → Hibernate parsing crash. r.id = ?1 comparing Integer to String → type mismatch crash.</p><p><strong>After (fixed):</strong></p><pre>@Query(&quot;SELECT r FROM RequestDetails r &quot; +<br>       &quot;WHERE (r.name LIKE CONCAT(&#39;%&#39;, :name, &#39;%&#39;) OR CAST(r.id AS string) = :name) &quot; +<br>       &quot;AND r.project IN :projects &quot; +<br>       &quot;AND r.requestStatusId IN :statusIds &quot; +<br>       &quot;AND r.requestTypeId = :requestTypeId &quot; +<br>       &quot;ORDER BY r.requestCreationTime DESC&quot;)<br>Page&lt;RequestDetails&gt; searchWithAll(<br>        @Param(&quot;name&quot;) String name,<br>        @Param(&quot;projects&quot;) List&lt;String&gt; projects,<br>        @Param(&quot;statusIds&quot;) List&lt;Integer&gt; statusIds,<br>        @Param(&quot;requestTypeId&quot;) Integer requestTypeId,<br>        Pageable page<br>);</pre><p>Named parameters, @Param annotations, and a proper CAST for the type mismatch. Clean, readable, and Hibernate doesn&#39;t have to count anything.</p><h3>What This Taught Me</h3><p>I’ve been studying Spring Boot from books, and that’s been great for building foundations. But hitting an actual bug at work — one with a stack trace I couldn’t read, a fix I didn’t understand, and an error message that meant nothing to me — that taught me something different.</p><p>Books give you the concept. Production gives you the edge cases, the Hibernate 5 quirks, the lazy validation that lets broken queries slip through startup. Both matter.</p><p>If you hit the Unexpected gap in ordinal parameter labels error — you now know exactly why it happens and how to fix it.</p><h3>What’s Next</h3><p>I’ll be heading back to the study series soon. Spring AOP is next — and after understanding BeanPostProcessors from the <a href="https://medium.com/@ziad-sharara/i-finally-understood-ioc-and-di-in-spring-64aa320ad0b6">last article</a>, I’m actually excited to see how proxies power the whole AOP model.</p><p>But I’ll keep writing these “from the trenches” posts whenever something breaks and I learn from it. They might be the most useful ones.</p><p><em>Stack: Spring Boot 2.6.1, Hibernate 5.6.1, Spring Data JPA 2.6.0, Java 17.</em></p><p><em>If you’ve hit a similar Hibernate quirk, drop it in the comments — I’d genuinely like to know what else this thing surprises people with.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a84343e6213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wait, SQL Doesn’t Run in the Order You Write It?]]></title>
            <link>https://ziad-sharara.medium.com/wait-sql-doesnt-run-in-the-order-you-write-it-77e67e43ca18?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e67e43ca18</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[logical-processing-order]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[query]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 18:40:47 GMT</pubDate>
            <atom:updated>2026-06-06T18:40:47.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o77CrEJmmh3U5T0wcZ4i4A.png" /></figure><blockquote><strong><em>Quick context:</em></strong><em> I recently took a break from studying Spring Boot to go back and refresh my SQL. Turns out I forgot more than I thought, so I bought a course called </em>The Art of Querying SQL<em> and went through it. While studying, I came across a concept that genuinely surprised me — and I almost missed it because it seems obvious until you really think about it.</em></blockquote><blockquote><em>Before writing this article, I posted a question on X — two SQL queries that look almost identical, and asked: </em>what’s the difference, and why?<em> This article is the answer. If you saw that post, welcome. If not, stick around — you’re about to understand something that will change how you read SQL queries forever.</em></blockquote><h3>The Question That Started This</h3><p>Look at these two queries:</p><pre>-- Query A<br>SELECT *<br>FROM users<br>LEFT JOIN orders<br>  ON users.id = orders.user_id<br>  AND orders.id IS NOT NULL;</pre><pre>-- Query B<br>SELECT *<br>FROM users<br>LEFT JOIN orders<br>  ON users.id = orders.user_id<br>WHERE orders.id IS NOT NULL;</pre><p>At first glance? They look the same. Same tables, same join condition, same filter. The only difference is whether orders.id IS NOT NULL sits inside the ON or after a WHERE.</p><p>Spoiler: <strong>they return completely different results.</strong></p><p>And the reason why comes down to one concept — “<strong>Logical Processing Order”</strong>.</p><h3>SQL Lies to Your Face (Kind Of)</h3><p>Here’s the thing nobody tells you when you first learn SQL:</p><p><strong>The order you <em>write</em> a SQL query is NOT the order the database <em>executes</em> it.</strong></p><p>You write it like this:</p><pre>SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY</pre><p>But the database actually runs it in this order:</p><pre>FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY</pre><p>This is called the <strong>Logical Processing Order</strong> — the sequence in which the database engine mentally processes each clause before handing you back a result.</p><p>Let that sink in for a second.</p><p>You write SELECT first. It runs last. You write WHERE after FROM. It runs after JOIN.</p><p>This isn’t a bug or a quirk — it’s by design, and once you understand it, a whole bunch of confusing SQL behavior suddenly makes perfect sense.</p><h3>Let’s Walk Through It Step by Step</h3><p>Think of running a SQL query like building a table from scratch in phases. Each phase takes what the previous one produced and does something to it.</p><h3>Step 1 — FROM: Pick Your Starting Table</h3><pre>FROM users</pre><p>The database starts here. It grabs the users table and says <em>&quot;okay, this is our working dataset.&quot;</em> Nothing is filtered, nothing is joined yet. Just the raw table.</p><h3>Step 2 — JOIN: Bring in the Other Table</h3><pre>LEFT JOIN orders ON users.id = orders.user_id</pre><p>Now the database combines users with orders. This is where things get interesting — and this is where the ON clause lives.</p><p>The ON clause doesn&#39;t just define <em>how</em> to join — it defines <em>which rows from the right table participate in the join at all</em>.</p><p>With a <strong>LEFT JOIN</strong> specifically, the behavior is:</p><ul><li>Every row from the <strong>left table</strong> (users) is preserved. Always.</li><li>The ON condition only determines which rows from the <strong>right table</strong> (orders) get matched.</li><li>If no match is found → the user still appears, but with NULL in all the order columns.</li></ul><p>This is the key insight for our question. Keep it in mind.</p><h3>Step 3 — WHERE: Filter the Result</h3><pre>WHERE orders.id IS NOT NULL</pre><p>This runs <em>after</em> the join is complete. At this point, you already have a combined table — users with their matched orders (or NULLs where there was no match). The WHERE clause then walks through that result and throws away any row that doesn&#39;t meet the condition.</p><h3>Steps 4–8 — The Rest</h3><pre>GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY</pre><p>These run in order after WHERE. GROUP BY groups rows, HAVING filters groups (like WHERE but for groups), SELECT picks which columns you actually want, DISTINCT removes duplicates, and ORDER BY sorts the final result.</p><h3>Now Let’s Answer the Question</h3><p>Back to our two queries. Let’s use real data to see what happens.</p><p><strong>Our tables:</strong></p><p>users:</p><pre>id | name<br>---+-------<br>1  | Ahmed<br>2  | Sara<br>3  | Omar</pre><p>orders:</p><pre>id   | user_id | item<br>-----+---------+--------<br>101  | 1       | Laptop<br>NULL | 2       | Phone<br> —   | —       | (Omar has no orders)</pre><h3>Query A — Condition in the ON clause</h3><pre>SELECT *<br>FROM users<br>LEFT JOIN orders<br>  ON users.id = orders.user_id<br>  AND orders.id IS NOT NULL;</pre><p><strong>What happens at the JOIN phase:</strong></p><p>The database tries to match each user to orders. But the join condition is now: users.id = orders.user_id AND orders.id IS NOT NULL</p><p>So for Sara (user 2): her order exists, but orders.id is NULL — so it <em>doesn&#39;t qualify</em> as a match. No match found.</p><p>But remember: <strong>LEFT JOIN always preserves the left table.</strong> So Sara still shows up — just with NULLs in the order columns.</p><p><strong>Result:</strong></p><pre>id | name  | order_id | item<br>---+-------+----------+--------<br>1  | Ahmed | 101      | Laptop<br>2  | Sara  | NULL     | NULL<br>3  | Omar  | NULL     | NULL</pre><p>All three users appear. The filter only affected <em>which orders got matched</em>, not which users show up.</p><h3>Query B — Condition in the WHERE clause</h3><pre>SELECT *<br>FROM users<br>LEFT JOIN orders<br>  ON users.id = orders.user_id<br>WHERE orders.id IS NOT NULL;</pre><p><strong>What happens at the JOIN phase:</strong></p><p>The join runs with just users.id = orders.user_id. After this, the result looks like:</p><pre>id | name  | order_id | item<br>---+-------+----------+--------<br>1  | Ahmed | 101      | Laptop<br>2  | Sara  | NULL     | NULL<br>3  | Omar  | NULL     | NULL</pre><p><strong>Then WHERE runs:</strong></p><p>orders.id IS NOT NULL filters this result. Sara and Omar both have NULL for orders.id — and NULL IS NOT NULL is false — so they get removed.</p><p><strong>Final result:</strong></p><pre>id | name  | order_id | item<br>---+-------+----------+--------<br>1  | Ahmed | 101      | Laptop</pre><p>Only Ahmed survives. Your LEFT JOIN just silently became an INNER JOIN.</p><h3>The One-Line Summary</h3><blockquote><strong><em>“ON” filters which rows from the right table participate in the join.</em></strong><em> “</em><strong><em>WHERE” filters the entire result after the join is done.</em></strong></blockquote><p>For INNER JOINs, this distinction doesn’t change your output — both end up doing the same thing. But for LEFT (or RIGHT) JOINs, it’s completely different behavior, and getting it wrong is a quiet, nasty bug because your query won’t error — it’ll just return fewer rows than you expected.</p><h3>A Practical Rule to Remember</h3><p>Ask yourself: <em>“Do I want to keep all rows from the left table regardless?”</em></p><ul><li><strong>Yes</strong> → put conditions that belong to the right table in the ON clause</li><li><strong>No, I only want matched rows</strong> → use WHERE (or just use INNER JOIN and be honest about it)</li></ul><h3>Why Does This Matter More Than You Think?</h3><p>Once you internalize the logical processing order, a bunch of other SQL behaviors stop being confusing:</p><ul><li><strong>Why can’t I use a SELECT alias in WHERE?</strong> Because WHERE runs before SELECT. The alias doesn&#39;t exist yet.</li><li><strong>Why does HAVING exist if WHERE already filters?</strong> Because GROUP BY runs after WHERE. If you want to filter groups, you need HAVING — which runs after grouping.</li><li><strong>Why does </strong><strong>ORDER BY see my SELECT aliases?</strong> Because it&#39;s the last thing that runs. By then, your aliases exist.</li></ul><p>Every weird SQL rule that felt arbitrary before? It’s just the logical processing order doing its job.</p><h3>What I’m Studying Right Now</h3><p>This came out of <em>The Art of Querying SQL</em> course, which I picked up after realizing my SQL fundamentals had gotten rusty. I’m also starting the SQL50 challenge on LeetCode to keep the practice going — theory is great, but you learn a different way when you’re staring at a failing test case.</p><h3>What’s Next</h3><p>I’ll be heading back to the Spring Boot series soon — next up is AOP (Aspect-Oriented Programming) and how Spring uses proxies to add behavior to your beans without touching your code. If you’ve been following the series, <a href="https://medium.com/@ziad-sharara/i-finally-understood-ioc-and-di-in-spring-64aa320ad0b6">you’ll want that one</a>.</p><p>But I’ll keep mixing in SQL and other things I pick up along the way. The goal was never “only Spring” — it’s documenting the whole journey.</p><p><em>If something here is wrong or you want to argue about it — the comments are right there. I’d actually love it.</em></p><p><em>Resources: The Art of Querying SQL course, Bits &amp; Pixels</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e67e43ca18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finally Understood Spring #2: The Complete Spring Bean Lifecycle.]]></title>
            <link>https://ziad-sharara.medium.com/i-finally-understood-what-spring-does-at-startup-4749b9bd9245?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4749b9bd9245</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 23:46:40 GMT</pubDate>
            <atom:updated>2026-06-03T22:53:36.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*907GhxMPxYAM05HGPWZ6pg.png" /></figure><blockquote><strong><em>Before we start: Someone replied to my last post on X saying: “Nice work, your next write up should be about how IoC, DI and the bean creation process works behind the scenes.” So here we are. If you haven’t read the first article about what IoC and DI are and how to wire beans, I’d start there — this one picks up right where it left off.</em></strong></blockquote><h3>You Know the What. Now Let’s Talk About the How.</h3><p>In the last post, we talked about the Spring Context as a “big smart container” that manages your beans and injects them where needed. And that’s a fine mental model to <em>use</em> Spring.</p><p>But I got curious. When my app boots up and Spring somehow knows to create a UserService, inject a UserRepository into it, and have everything ready before my first request comes in — what is actually happening step by step?</p><p>So I went digging. And this post is what I found.</p><h3>The Cast of Characters</h3><p>Before we trace through the lifecycle, let me introduce the main players:</p><p><strong>BeanFactory</strong> — the most basic interface. It&#39;s the actual IoC container at its core. It can create and return beans. That&#39;s pretty much it.</p><p><strong>ApplicationContext</strong> — think of it as BeanFactory with everything else on top. It adds event publishing, internationalization, and most importantly for us — it eagerly creates and wires all your singleton beans at startup rather than lazily on demand. In real Spring apps, this is what you&#39;re actually using.</p><p><strong>BeanDefinition</strong> — before a bean is created, Spring builds a metadata object for it. This holds everything Spring knows about the bean: its class, its scope, its dependencies, any initialization methods. Think of it as the <em>blueprint</em> before construction starts.</p><p><strong>BeanPostProcessor</strong> — a hook that lets you intercept the bean creation process and do something to a bean before or after it&#39;s initialized. This is the secret engine behind @Autowired, @Transactional, and AOP. We&#39;ll come back to this one — it&#39;s important.</p><h3>Step-by-Step: What Happens When Your App Boots</h3><p>Let’s say you have a simple Spring app. The moment you run it, here’s what Spring does behind the scenes:</p><h3>Phase 1 : Reading &amp; Building “BeanDefinitions”</h3><p>Spring starts by scanning your code. It reads your @Configuration classes, finds every @Bean method, scans for @Component / @Service / @Repository annotated classes, and for each one it builds a BeanDefinition object.</p><p>At this point, <strong>no beans are created yet</strong>. Spring is just reading blueprints.</p><pre>// Spring reads this and creates a BeanDefinition for &quot;userService&quot;<br>// It notes: class = UserService,<br>//            scope = singleton,<br>//            depends on = UserRepository<br>@Service<br>public class UserService {<br>    private final UserRepository userRepository;<br><br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br>}</pre><p>It’s like an architect reading all the floor plans before breaking ground. Spring needs to know about <em>everything</em> before it starts building <em>anything</em> — because it needs to figure out the dependency order.</p><h3>Phase 2 : Resolving the Dependency Graph</h3><p>Now Spring looks at all the BeanDefinitions and figures out: &quot;If UserService needs a UserRepository, I need to create UserRepository first.&quot;</p><p>It builds an internal dependency graph and determines the right creation order. This is also the phase where Spring detects <strong>circular dependencies</strong> with constructor injection and blows up immediately with a clear error — which is exactly what you want.</p><h3>Phase 3 : Instantiation</h3><p>Spring starts creating beans in the right order. For each bean, it calls the constructor.</p><pre>// Spring essentially does this for you<br>UserRepository repo = new UserRepository();<br>UserService service = new UserService(repo);</pre><p>But here’s where it gets interesting — Spring doesn’t call new directly. It goes through its BeanFactory machinery, which means every creation is intercepted, tracked, and can be customized.</p><h3>Phase 4 : Dependency Population (DI happens here)</h3><p>For field injection and setter injection cases, this is the phase where Spring walks through each bean and injects the required dependencies — setting fields or calling setters.</p><p>With constructor injection, this already happened in Phase 3 (the dependency was passed to the constructor). This is one more reason constructor injection is cleaner.</p><p>“DI and instantiation happen in a single step.”</p><h3>Phase 5 : BeanPostProcessors Do Their Thing</h3><p>This is the phase most Spring students never hear about, and it explains <em>so much</em> of how Spring’s magic features work.</p><p>After a bean is created and its dependencies are injected, Spring passes it through every registered BeanPostProcessor. Each one gets two shots at the bean:</p><ul><li>postProcessBeforeInitialization() — runs before any @PostConstruct or afterPropertiesSet() calls</li><li>postProcessAfterInitialization() — runs after initialization is complete</li></ul><p>Here’s the key insight: <strong>@Autowired resolution is handled by a </strong><strong>BeanPostProcessor</strong> called AutowiredAnnotationBeanPostProcessor. When Spring creates a bean, this processor scans its fields and methods for @Autowired, finds the matching beans in the context, and injects them.</p><p>@Transactional? Also a BeanPostProcessor. AOP proxies? Same story. These aren&#39;t built into the core container — they&#39;re extensions that plug in through this hook system.</p><pre>Bean instantiated<br>      ↓<br>BeanPostProcessor.postProcessBeforeInitialization()<br>      ↓<br>@PostConstruct / afterPropertiesSet() called<br>      ↓<br>BeanPostProcessor.postProcessAfterInitialization()  ← proxy wrapping happens here<br>      ↓<br>Bean is READY in context</pre><h3>Phase 6 : The Bean is Ready</h3><p>Once it’s passed through all the post-processors, the bean is placed in the context — specifically in the “<strong>singleton” cache</strong> (assuming singleton scope, which is the default). Every future request for this bean type returns the same cached instance.</p><p>This is why Spring beans are fast at runtime.</p><p>“All the heavy creation work happens once at startup.”</p><h3>The CGLIB Proxy Mystery — Why @Bean Methods Don’t Create Duplicate Objects</h3><p>In the first article, I mentioned that when you call a @Bean method from another @Bean method, Spring doesn&#39;t actually create a new object. I called it &quot;Spring&#39;s proxy magic.&quot; Let me explain what&#39;s actually happening.</p><p>When Spring processes a @Configuration class, it doesn&#39;t use your class directly. It creates a <strong>CGLIB subclass</strong> of it — a dynamically generated proxy that extends your configuration class and overrides your @Bean methods.</p><pre>@Configuration<br>public class AppConfig {<br><br>    @Bean<br>    public UserRepository userRepository() {<br>        return new UserRepository(); // looks like a plain new call<br>    }<br><br>    @Bean<br>    public UserService userService() {<br>        return new UserService(userRepository()); // calling the method again?<br>    }<br>}</pre><p>Here’s what the CGLIB proxy’s overridden userRepository() method roughly does:</p><pre>1. Is the &#39;userRepository&#39; bean already in the singleton cache?<br><br>   → YES: return the cached instance<br><br>   → NO: call the original method, cache the result, return it</pre><p>So when userService() calls userRepository(), it&#39;s not calling your original method — it&#39;s calling the proxy&#39;s version. The proxy checks the cache, finds the existing bean, and returns it. No duplicate creation.</p><p>This is also why @Configuration classes must be non-final and non-private — CGLIB needs to subclass them. If you use @Configuration(proxyBeanMethods = false), you opt out of this behavior (useful for performance in some cases, but you lose the singleton guarantee for @Bean method calls).</p><h3>Bean Scope — Not All Beans Live the Same Way</h3><p>Quick but important: when we say a bean is “in the context,” the default is “<strong>singleton”</strong> scope — one instance per application context, created once, reused everywhere.</p><p>But scope is configurable:</p><pre>@Bean<br>@Scope(&quot;prototype&quot;)<br>public ReportGenerator reportGenerator() {<br>    return new ReportGenerator();<br>}</pre><p>Scope Behavior singleton One instance per ApplicationContext (default) prototype New instance every time the bean is requested request One instance per HTTP request (web apps) session One instance per HTTP session (web apps)</p><p>Prototype scope means Spring creates a new instance every time someone asks for it — but it <strong>doesn’t manage the lifecycle after creation</strong>. It’s on you to clean up prototype beans. This trips up sometimes.</p><h3>What Happens at Shutdown</h3><p>Just like Spring hooks into bean creation, it hooks into destruction too. If your bean implements DisposableBean or has a @PreDestroy annotated method, Spring calls it when the context is closing — giving your beans a chance to clean up resources (close connections, flush buffers, etc.).</p><pre>@Component<br>public class DatabaseConnectionPool {<br><br>    @PostConstruct<br>    public void init() {<br>        System.out.println(&quot;Pool initialized — connections ready&quot;);<br>    }<br><br>    @PreDestroy<br>    public void cleanup() {<br>        System.out.println(&quot;Closing all connections...&quot;);<br>    }<br>}</pre><p>The full lifecycle in one picture:</p><pre>Class scanning → BeanDefinition created<br>      ↓<br>Dependency graph resolved<br>      ↓<br>Bean instantiated (constructor called)<br>      ↓<br>Dependencies injected (setter/field if applicable)<br>      ↓<br>BeanPostProcessor: beforeInitialization<br>      ↓<br>@PostConstruct / afterPropertiesSet()<br>      ↓<br>BeanPostProcessor: afterInitialization (proxies created here)<br>      ↓<br>Bean in singleton cache — READY<br>      ↓<br>      ... app runs ...<br>      ↓<br>Context shutting down<br>      ↓<br>@PreDestroy / destroy()<br>      ↓<br>Bean destroyed</pre><h3>Full Example: Watching the Lifecycle Happen</h3><p>Here’s a complete, runnable example that logs each lifecycle phase so you can actually see the order things happen:</p><pre>// The repository layer<br>@Repository<br>public class UserRepository {<br><br>    public UserRepository() {<br>        System.out.println(&quot;[UserRepository] Instantiated&quot;);<br>    }<br>}<br><br>// The service layer<br>@Service<br>public class UserService {<br><br>    private final UserRepository userRepository;<br><br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>        System.out.println(&quot;[UserService] Instantiated with UserRepository: &quot; + userRepository);<br>    }<br><br>    @PostConstruct<br>    public void init() {<br>        System.out.println(&quot;[UserService] @PostConstruct — fully initialized&quot;);<br>    }<br><br>    @PreDestroy<br>    public void cleanup() {<br>        System.out.println(&quot;[UserService] @PreDestroy — shutting down&quot;);<br>    }<br>}<br><br>// A custom BeanPostProcessor so you can see the hook in action<br>@Component<br>public class LifecycleLogger implements BeanPostProcessor {<br><br>    @Override<br>    public Object postProcessBeforeInitialization(Object bean, String beanName) {<br>        if (bean instanceof UserService) {<br>            System.out.println(&quot;[BeanPostProcessor] BEFORE init: &quot; + beanName);<br>        }<br>        return bean;<br>    }<br><br>    @Override<br>    public Object postProcessAfterInitialization(Object bean, String beanName) {<br>        if (bean instanceof UserService) {<br>            System.out.println(&quot;[BeanPostProcessor] AFTER init: &quot; + beanName);<br>        }<br>        return bean;<br>    }<br>}<br><br>// The main entry point<br>@SpringBootApplication<br>public class Main {<br>    public static void main(String[] args) {<br>        ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args);<br>        ctx.close(); // triggers @PreDestroy<br>    }<br>}</pre><p><strong>Console output:</strong></p><pre>[UserRepository] Instantiated<br>[UserService] Instantiated with UserRepository: com.example.UserRepository@...<br>[BeanPostProcessor] BEFORE init: userService<br>[UserService] @PostConstruct — fully initialized<br>[BeanPostProcessor] AFTER init: userService<br>... app runs ...<br>[UserService] @PreDestroy — shutting down</pre><p>Run this yourself and you’ll have an intuitive feel for the lifecycle that no diagram can give you.</p><h3>What This Changes About How I Think About Spring</h3><p>Before going into this, Spring felt like a black box that somehow made everything appear. Now I see it as a very deliberate, phased system:</p><ul><li><strong>Scan</strong> — know what exists</li><li><strong>Plan</strong> — figure out the order</li><li><strong>Build</strong> — create and wire</li><li><strong>Extend</strong> — run post-processors (this is where the real magic like @Autowired, AOP, and transactions plug in)</li><li><strong>Serve</strong> — live in the singleton cache</li><li><strong>Clean up</strong> — graceful shutdown</li></ul><p>Understanding BeanPostProcessor in particular was the &quot;aha&quot; moment. It demystifies so much of what feels like Spring voodoo. @Transactional wraps your bean in a proxy? That&#39;s a BeanPostProcessor. @Autowired injects dependencies after construction? BeanPostProcessor. AOP advice gets woven around your methods? Also a BeanPostProcessor.</p><p>Which is a perfect segue into what’s coming next.</p><h3>What’s Next</h3><p>Now that we understand <em>how</em> Spring creates and wires beans, and we know that proxies are the mechanism Spring uses to add behavior around your beans — the next logical step is <strong>AOP (Aspect-Oriented Programming)</strong>.</p><p>AOP is what you reach for when you want to add cross-cutting behavior (logging, security checks, transactions) to your methods <em>without polluting your business logic</em>. And now that you know beans go through a post-processor phase where Spring can wrap them in proxies — you already have the mental model to understand how AOP works under the hood.</p><p>That one’s going to be a fun post to write.</p><p><em>This is part of an ongoing series where I document everything I learn on my Backend Engineering journey — as I learn it. If something here is wrong, tell me in the comments. That’s literally why I write these.</em></p><ul><li><em>7References: Spring Start Here by Laurentiu Spilca (Manning Publications)</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4749b9bd9245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finally Understood Spring #1: The Spring Context, IoC, and Dependency Injection Explained.]]></title>
            <link>https://ziad-sharara.medium.com/i-finally-understood-ioc-and-di-in-spring-64aa320ad0b6?source=rss-8c9e73dc1ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/64aa320ad0b6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ziad Sharara]]></dc:creator>
            <pubDate>Wed, 27 May 2026 16:56:42 GMT</pubDate>
            <atom:updated>2026-06-03T22:56:29.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*3MJ6tHJmh96kaMf_Z9BAHQ.png" /></figure><blockquote><strong><em>A little context before we start:</em></strong><em> I’m currently working through </em>Spring Start Here<em> by Laurentiu Spilca, and Chapter 3 genuinely shifted how I think about how objects talk to each other inside a Spring application. I wanted to write this down — partly as notes for myself, partly to share what clicked for me. If you’re also learning Spring, I hope this saves you some of the confusion I had.</em></blockquote><h3>The Problem: Objects Need Each Other</h3><p>Here’s the thing about real applications — no object lives alone.</p><p>You have a Service that needs a Repository. You have a Controller that needs a Service. Everything depends on something else. So the question becomes: <em>who&#39;s responsible for connecting all these pieces together?</em></p><p>In plain Java, you’d do it manually:</p><pre>Repository repo = new Repository();<br>Service service = new Service(repo);<br>Controller controller = new Controller(service);</pre><p>Simple enough. But as your app grows, this gets messy fast. You’re manually managing the life-cycle of every object, making sure things are created in the right order, and passing references around everywhere. And what happens when you need to swap one implementation for another? You go hunting through your codebase.</p><p>This is exactly the problem Spring’s <strong>IoC container</strong> (the Spring Context) was built to solve.</p><h3>IoC and DI — What Do These Terms Actually Mean?</h3><p>These two acronyms show up everywhere in Spring docs, and they’re related but not the same thing.</p><p><strong>“IoC — Inversion of Control”</strong> is the principle. Normally, <em>your code</em> controls the flow — it creates objects, wires them together, calls methods. With IoC, you <em>invert</em> that control. You hand it over to a framework (Spring, in our case). Spring becomes responsible for creating and managing your objects.</p><p><strong>“DI — Dependency Injection”</strong> is how Spring <em>implements</em> IoC. Instead of your objects going out and fetching what they need, Spring <em>injects</em> the dependencies into them. You declare what you need; Spring figures out how to provide it.</p><p>A nice analogy: think of it like a restaurant kitchen. Normally, every cook would go to the market themselves to buy ingredients (your code managing its own dependencies). With DI, there’s a central supply team (Spring) that stocks each station with exactly what it needs before service starts.</p><p>The objects Spring manages are called “<strong>beans”</strong>, and they all live inside the “<strong>Spring Context”</strong> — basically a big, smart container that knows about all your application’s components and their relationships.</p><h3>Three Ways to Wire Beans in the Spring Context</h3><p>Once you have beans registered in the context, you need to tell Spring how they relate to each other. There are three approaches, and each has its place.</p><h3>Approach 1: Calling the @Bean Method Directly</h3><p>This is the most explicit way. If you’re configuring your beans in a @Configuration class using @Bean methods, you can simply call one method from another:</p><pre>@Configuration<br>public class AppConfig {    <br><br>    @Bean<br>    public Repository repository() {<br>        return new Repository();<br>    }<br><br>    @Bean<br>    public Service service() {<br>        return new Service(repository()); // calling the @Bean method directly<br>    }<br>}</pre><p>Here’s the thing that surprised me: even though it <em>looks</em> like you’re calling repository() and creating a new object, Spring intercepts that call. If the repository bean already exists in the context, Spring returns the existing instance rather than creating a new one. This is Spring&#39;s “<strong>proxy magic”</strong> at work.</p><p><strong>When to use it:</strong> When you’re already in a @Configuration class and want maximum clarity about which bean is being used. It reads naturally — almost like reading a dependency graph.</p><p><strong>The downside:</strong> It only works within @Configuration classes. And if you&#39;re not careful, it can <em>look</em> like it&#39;s creating a new object every time, which confuses newcomers (and past-me).</p><h3>Approach 2: Defining a Parameter on the @Bean Method</h3><p>A cleaner alternative — just add the dependency as a parameter to your @Bean method:</p><pre>@Configuration<br>public class AppConfig {<br><br>    @Bean<br>    public Repository repository() {<br>        return new Repository();<br>    }<br><br>    @Bean<br>    public Service service(Repository repository) { // Spring injects this<br>        return new Service(repository);<br>    }<br>}</pre><p>Spring sees that service() has a Repository parameter, looks for a bean of that type in the context, and injects it automatically. You don&#39;t call anything manually.</p><p><strong>When to use it:</strong> When your @Bean methods are in different configuration classes, or when you want the method signature to clearly document what the bean depends on.</p><p><strong>The downside:</strong> If Spring can’t find a matching bean — or finds too many — it’ll throw an exception at startup. Which is actually a <em>good</em> thing (fail fast), but you need to be aware of it.</p><h3>Approach 3: @Autowired — Three Flavors</h3><p>@Autowired is the most common approach in real-world Spring apps, and it comes in three forms. Each has a different feel and a different recommended use case.</p><h4>3a. “Field Injection”</h4><pre>@Component<br>public class Service {<br><br>    @Autowired<br>    private Repository repository; // Spring injects directly into this field<br>}</pre><p>This is the quickest to write — just slap @Autowired on a field. Spring injects the value after creating the object.</p><p><strong>When to use it:</strong> Honestly? Mostly in small demos, proof-of-concept projects, or when you’re just trying something out quickly.</p><p><strong>Why it’s not great for production:</strong></p><ul><li>You can’t make the field final, which means the dependency <em>could</em> change after object creation.</li><li>It makes the class harder to test — you can’t inject mock dependencies through a constructor in a plain unit test; you’d need Spring’s test context.</li><li>It hides dependencies. Looking at the class signature tells you nothing about what it needs.</li></ul><h4>3b. Constructor Injection ✅ (The Recommended Way)</h4><pre>@Component<br>public class Service {<br><br>    private final Repository repository;<br><br>    @Autowired<br>    public Service(Repository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>Spring calls the constructor and injects the Repository bean as an argument.</p><blockquote><strong><em>Quick note:</em></strong><em> In newer versions of Spring (4.3+), if your class has only </em>one<em> constructor, the </em><em>@Autowired annotation is optional — Spring will figure it out automatically.</em></blockquote><p><strong>Why this is the best approach?</strong></p><ul><li>The field can be final — the dependency is set once and never changes. “Immutability is your friend.”</li><li>The class <em>clearly declares</em> its dependencies through its constructor. Reading the constructor tells you exactly what this class needs to work.</li><li>It’s easy to test — you can just call new Service(mockRepository) in your unit tests without Spring at all.</li><li>Spring will detect “<strong>circular dependencies”</strong> at startup and throw an exception immediately, rather than letting them silently cause problems at runtime.</li></ul><p>This is what you’ll see in most well-maintained Spring codebases.</p><h4>3c. Setter Injection</h4><pre>@Component<br>public class Service {<br><br>   private Repository repository;<br><br>    @Autowired<br>    public void setRepository(Repository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>Spring creates the object first, then calls the setter to inject the dependency.</p><p><strong>When to use it:</strong> For <em>optional</em> dependencies — ones that have a sensible default and don’t always need to be provided. You can mark these with @Autowired(required = false).</p><p><strong>Why it’s rare in practice:</strong> Most dependencies aren’t optional. And unlike constructor injection, it doesn’t enforce immutability or make dependencies obvious from the outside. You’ll encounter it occasionally when working with legacy code or specific frameworks, but it’s not something you’d reach for by default.</p><h3>Choosing Between Them — A Quick Decision Guide</h3><p>Situation Recommended Approach Quick demo or POC Field injection (just get it working) Production code, required dependency Constructor injection Optional/configurable dependency Setter injection @Configuration class, explicit wiring Direct @Bean method call or parameter</p><p>My personal take: <strong>default to constructor injection almost always.</strong> It makes your dependencies explicit, your objects immutable, and your tests simple. You’ll thank yourself later.</p><h3>When Spring Gets Confused: Ambiguity and “Circular Dependencies”</h3><p>Two things that will absolutely bite you if you’re not aware of them.</p><h3>The Ambiguity Problem</h3><p>What happens if Spring finds <em>multiple</em> beans of the same type in the context?</p><pre>@Bean<br>public Renderer htmlRenderer() { return new HtmlRenderer(); }<br>@Bean<br>public Renderer pdfRenderer() { return new PdfRenderer(); }</pre><p>Now, if some other bean needs a Renderer injected, Spring panics. It doesn&#39;t know which one to pick, and it&#39;ll throw a NoUniqueBeanDefinitionException.</p><p>You have two ways to fix this:</p><p><strong>Option A: @Primary</strong> — mark one bean as the default choice:</p><pre>@Bean<br>@Primary<br>public Renderer htmlRenderer() { return new HtmlRenderer(); }</pre><p>Now when Spring needs to inject a Renderer and no specific name is requested, it&#39;ll use htmlRenderer.</p><p><strong>Option B: @Qualifier</strong> — be explicit about which bean you want:</p><pre>@Autowired<br>@Qualifier(&quot;pdfRenderer&quot;)<br>private Renderer renderer;</pre><p>Use @Primary when there&#39;s a clear &quot;default&quot; option that most callers want. Use @Qualifier when you need precise control over which bean goes where.</p><h3>The Circular Dependency Problem</h3><p>A circular dependency happens when Bean A depends on Bean B, and Bean B depends on Bean A:</p><pre>ServiceA → needs → ServiceB<br>ServiceB → needs → ServiceA</pre><p>Spring cannot resolve this. It tries to create ServiceA, realizes it needs ServiceB, starts creating ServiceB, realizes it needs ServiceA... and gives up with a BeanCurrentlyInCreationException.</p><p>The fix isn’t a Spring trick — it’s a design signal. Circular dependencies usually mean your classes are doing too much, or the responsibility split isn’t quite right. The solution is typically to:</p><ul><li>Extract the shared logic into a third component that both can depend on.</li><li>Reconsider which class actually owns the behavior causing the cycle.</li></ul><p>Spring with constructor injection will catch this immediately at startup, which is one more reason to prefer it.</p><h3>Full Code Example: Putting It All Together</h3><p>Here’s a realistic (if simplified) example using constructor injection — the production-ready way:</p><pre>// The data layer<br>@Repository<br>public class UserRepository {<br><br>    public User findById(Long id) {<br>        // imagine a real DB call here<br>        return new User(id, &quot;Ahmed&quot;);<br>    }<br>}<br><br>// The business logic layer<br>@Service<br>public class UserService {<br><br>   private final UserRepository userRepository;<br><br>   // Constructor injection — Spring sees one constructor, injects automatically<br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>    public User getUser(Long id) {<br>        return userRepository.findById(id);<br>    }<br>}<br><br>// The presentation layer<br>@RestController<br>public class UserController {<br>    private final UserService userService;<br><br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public User getUser(@PathVariable Long id) {<br>        return userService.getUser(id);<br>    }<br>}</pre><p>Spring wires all of this together at startup. You never write</p><p>new UserService(new UserRepository()).</p><p>Spring reads the constructors, figures out the dependency chain, creates everything in the right order, and hands you a fully assembled application.</p><h3>What Actually Clicked for Me</h3><p>When I first read about IoC, it sounded like an abstract principle that “enterprise” developers care about. But going through Chapter 3 made it concrete: Spring is essentially taking over the job of new so that <em>your</em> code doesn&#39;t have to care about construction and wiring.</p><p>The moment it clicked was realizing that with constructor injection, the class is completely honest about what it needs. No hidden state. No surprise fields. If a class has five constructor parameters, that’s Spring (and you) both knowing that maybe this class is doing too much.</p><p>DI isn’t just a framework feature — it’s a design philosophy that nudges you toward cleaner, more testable, more honest code.</p><h3>What’s Next</h3><p>This is part of my notes series as I work through <em>Spring Start Here</em>. Coming chapters cover Spring AOP, transactions, REST services with Spring MVC, and eventually Spring Boot. I’ll keep documenting what I learn as I go.</p><p>If something here is wrong or unclear, I’d genuinely love to know — drop a comment. I’m a student, not an expert, and this blog is as much for learning out loud as it is for sharing.</p><p><em>References: Spring Start Here by Laurentiu Spilca (Manning Publications)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64aa320ad0b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>