<?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 MRegra on Medium]]></title>
        <description><![CDATA[Stories by MRegra on Medium]]></description>
        <link>https://medium.com/@mregra-marcelo-silva?source=rss-f35fcd5cfe22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Na0JA6Y38Wwuxzs48Ef8Ow.jpeg</url>
            <title>Stories by MRegra on Medium</title>
            <link>https://medium.com/@mregra-marcelo-silva?source=rss-f35fcd5cfe22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:23:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mregra-marcelo-silva/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[The future of Software Engineers in a world filled with AI… and Zoom/Teams calls??]]></title>
            <link>https://medium.com/@mregra-marcelo-silva/the-future-of-software-engineers-in-a-world-filled-with-ai-and-zoom-calls-ed8f93e841b3?source=rss-f35fcd5cfe22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed8f93e841b3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[work-from-home]]></category>
            <dc:creator><![CDATA[MRegra]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 10:07:20 GMT</pubDate>
            <atom:updated>2025-11-29T10:20:35.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3J5umnZQQjwekeo2t-HXaQ.png" /></figure><pre>if (AI.level &lt; AGI) {<br>    engineer.role = &quot;architect + overseer&quot;;<br>    engineer.tasks = repeat(&quot;optimize&quot;, &quot;simplify&quot;, &quot;write better code&quot;);<br>} else if (AI.level &gt;= AGI) {<br>    engineer.role = &quot;visionary builder&quot;;<br>    engineer.tasks = imagination.generateProjects();<br>} else {<br>    throw new IKnowNothingException(&quot;The future isn’t yet defined&quot;);<br>}</pre><p>Every once in a while, technology rewrites the rules of its own game.</p><p>Electricity did. The internet did.</p><p><strong><em>And now… It’s AI’s turn.</em></strong></p><p>And at the same time, the office itself is dissolving into Wi-Fi, Teams links, and Slack threads.</p><p>So I’ve been asking myself:</p><ul><li>With AI writing more and more of the code…</li><li>And remote work is changing <em>where</em> we do it…</li></ul><p><strong>What happens to us?</strong> Do we all go back to the office? Will we get replaced by AI? Or do our jobs quietly turn into something else?</p><p>Let’s walk through it, using real data, not just vibes, and then I’ll finish with the concrete steps I’m taking to stay relevant for the next 10–20 years (hopefully 😅).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*_qa2hT_V3ppSOCM6.gif" /></figure><h3>The Shift Has Already Begun (And It’s Measurable)</h3><p>I don’t know when it started for you, but for me, it was the first time I saw an AI write a test <em>faster than I could</em>. Or even write code “exactly” as I wanted it… Exciting, promising, and scary all at once!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/0*YQ9LUw7s17a9KPPz.gif" /></figure><p>It wasn’t perfect, but it <em>worked.</em> And that quiet realization hit:</p><blockquote>This thing doesn’t sleep. It doesn’t forget imports (I mean, sometimes it does, but it is getting better… and fast). It doesn’t complain about refactoring.</blockquote><p>AI already writes boilerplate code, explains legacy code, and generates unit tests in seconds.</p><p><strong><em>That’s not just anecdotal:</em></strong></p><p>A controlled experiment from GitHub and Microsoft found that developers using Copilot completed a coding task <strong><em>55.8% faster</em></strong> than those without AI.(<a href="https://arxiv.org/abs/2302.06590">reference</a>). Independent analyses from McKinsey and others estimate <strong><em>20–45% productivity gains</em></strong> for software engineering when generative AI is integrated into the workflow, and surveys from JetBrains and Stack Overflow show that the majority of developers already use these tools daily and report meaningful time savings (references: <a href="https://www.nber.org/papers/w31161">Generative AI at Work | NBER</a>, <a href="https://www.jetbrains.com/lp/devecosystem-2023/">JetBrains</a>, <a href="https://www.deloitte.com/uk/en/Industries/technology/blogs/2024/the-future-of-coding-is-here-how-ai-is-reshaping-software-development.html">Delloit</a>)</p><p>So when we say “AI makes us 20–50% faster,” that’s not just marketing — it’s starting to show up in real experiments, company data, and independent research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*moS4aIzvxwBeSEWj.gif" /></figure><h4><strong><em>But here’s the twist.</em></strong></h4><p>AI <em>is</em> speeding up developers, sometimes dramatically, but teams aren’t becoming proportionally faster.</p><p><strong><em>Why?</em></strong></p><p>Because the bottleneck isn’t coding anymore.</p><p>According to Atlassian’s State of Developer Experience report, AI is saving developers <strong><em>10+ hours per week</em></strong>, but a big chunk of those gains gets swallowed by organizational mess: <strong><em>unclear requirements</em></strong>, <strong><em>meeting overload</em></strong>, <strong><em>poor documentation</em></strong>, <strong><em>fragmented tooling</em></strong>, and <strong><em>constant context switching</em></strong>. (<a href="https://www.itpro.com/software/development/atlassian-says-ai-has-created-an-unexpected-paradox-for-software-developers-theyre-saving-over-10-hours-a-week-but-theyre-still-overworked-and-losing-an-equal-amount-of-time-due-to-organizational-inefficiencies">reference</a>)</p><p>As the report puts it:</p><blockquote><strong>“the biggest productivity blockers are organizational, not technical.”</strong></blockquote><p>That’s where the future of work (remote vs office) collides with the future of engineering (AI vs humans).</p><h3>A personal observation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*0Btz8m76p5ZJIub9.gif" /></figure><p>I feel this in my day-to-day work.</p><p>I write faster and cleaner code now.</p><p>AI suggests patterns I wouldn’t have thought of, helps me avoid silly bugs, and speeds up test writing massively. Yes, it hallucinates sometimes, and those moments are painfully annoying, but overall, I’m a <strong>better, faster, more consistent developer</strong> because I use it.</p><ul><li>But if the requirements are vague?</li><li>Is the team’s communication fragmented?</li><li>If we’re jumping between meetings, tools, and threads all day?</li></ul><p>Even a 50% coding boost won’t save you.</p><p>AI does not yet automate the hard part… the part humans still own: <strong>clarity, coordination, architecture, decision-making, and deep thinking</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ShF4EC6aHpRChwwI.gif" /></figure><h4>Ah, the possible scenarios of AI…</h4><h3>Scenario 1: AI as Our Assistant</h3><p>The short-term, most realistic scenario.</p><p>AI becomes (<strong><em>already is, I’d say</em></strong>) our <strong>pair programmer</strong>, cleaning up the boring parts:</p><ul><li>Generating tests, configs, and docs.</li><li>Suggesting refactors before code review.</li><li>Scanning for security issues and performance regressions.</li></ul><p>In this world, engineers evolve into <strong>architects, reviewers, and decision-makers</strong>. We’ll spend less time typing syntax and more time reasoning about <strong>system behavior</strong>, <strong>edge cases</strong>, and <strong>long-term maintainability</strong>.</p><blockquote><strong>AI replaces repetition, not reasoning.</strong></blockquote><p>Ironically, it might make <em>clean architecture</em> and <em>simple design</em> even more valuable, because machines thrive in structured environments but fail miserably in chaos. <strong><em>The better your code, the better your AI assistant performs.</em></strong></p><h3>Scenario 2: AI as a Co-Engineer</h3><p>Fast forward a few years. AI starts designing systems, not just code snippets. <em>It gets promoted from “assistant” to “teammate”.</em></p><p>You’ll still set the vision, define requirements, constraints, priorities… but your “<strong><em>teammate</em></strong>” will propose class structures, pick data stores, and even spin up services.</p><p>It’s a collaboration, not a competition. You’ll delegate tasks like:</p><pre>ai.create(&quot;authentication microservice&quot;, secure = true);</pre><p>…and then focus on validation, integration, and behavior across the system.</p><p><strong><em>Your job?</em></strong></p><ul><li>Reject 7 bad designs and refine the 1 good one.</li><li>Think about failure modes, security, and trade-offs.</li><li>Align what’s being built with what actually matters to the business.</li></ul><p>Engineering becomes <strong>orchestration plus judgement</strong>: you’re less of a “feature factory worker” and more of a <strong>director</strong> in a very technical movie.</p><h3>Scenario 3: AI as the Engineer</h3><p>Now, let’s jump ahead, maybe 15 or 20 years (<em>maybe a lot sooner?… Who knows!</em>). AGI (or something close) writes full and complex systems end-to-end: <strong><em>design → build → deploy → test → optimize.</em></strong></p><blockquote><strong>That’s the moment people fear.</strong></blockquote><p>But look at past transitions:</p><ul><li><strong><em>Spreadsheets </em></strong>didn’t kill <strong><em>accountants</em></strong>; they killed calculators and paper ledgers.</li><li><strong><em>Compilers </em></strong>didn’t kill <strong><em>programmers</em></strong>; they killed machine code hand-typing for most people.</li><li><strong><em>Cloud </em></strong>didn’t kill <strong><em>sysadmins</em></strong>; it changed them into SREs, platform engineers, and DevOps.</li></ul><p>If we do reach that level, “software engineer” stops being about typing functions and starts being about:</p><ul><li><strong>Vision</strong>: What should we build and why?</li><li><strong>Ethics &amp; risk</strong>: Should we build this at all?</li><li><strong>Constraint design</strong>: Defining guardrails for AI systems.</li><li><strong>Interpretation</strong>: Turning messy human goals into precise system behavior.</li></ul><p>You go from <strong><em>“How do I implement this?”</em></strong> to <strong><em>“What are the most valuable systems we could bring into existence?”</em></strong></p><h3>Scenario 4: When AI Replaces Us Completely (The Thought Experiment)</h3><p>Let’s run the extreme case honestly:<br><strong>What if AI doesn’t just assist engineers… but eventually <em>replaces</em> the entire role?</strong></p><p>Not co-pilot.<br>Not a collaborator.<br>But fully autonomous software creation: requirements, architecture, code, tests, deployment, monitoring, all handled end-to-end by machines.</p><p>It sounds like science fiction, but it’s a useful thought experiment because it exposes something important:</p><ul><li>If engineering becomes fully automated, humans don’t become obsolete. We become <strong>unburdened</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*qXnomiiN9709E8k9.gif" /></figure><p>The value shifts from <em>how</em> to build software to <strong>what is worth building</strong>.</p><p>In this future:</p><ul><li>Innovation accelerates because ideas aren’t bottlenecked by implementation.</li><li>Anyone: a scientist, a teacher, a founder, an artist, can create complex systems instantly.</li><li>Humans move toward strategy, ethics, creativity, and decision-making.</li><li>The “engineer” role evolves into something closer to a <strong>systems thinker, product visionary, and curator of intelligent tools</strong>.</li></ul><p>The upside is simple but profound:</p><blockquote><strong>If AI takes over the manual craft of engineering, humans finally get to focus on purpose, intent, and imagination, the parts machines can’t define for us.</strong></blockquote><p>Even in the most extreme scenario, the question doesn’t become:<br><em>“Do engineers disappear?” </em>but rather <strong><em>“What new kind of builder do we become when the heavy lifting is gone?”</em></strong></p><h3>The Other Revolution: Remote Work, Offices, and Economic Reality</h3><p>While AI reshapes tasks, remote work is reshaping <em>where</em> those tasks happen.</p><p>A few things we know from data:</p><ul><li>The US Bureau of Labor Statistics looked across 61 industries and found that sectors with more remote work often saw <strong>no productivity penalty</strong>, and in some cases, higher total factor productivity during the pandemic years (reference: <a href="https://www.bls.gov/opub/btn/volume-13/remote-work-productivity.htm">bls.gov</a>)</li><li>A UK survey found <strong>52% of employers</strong> see home and office workers as equally productive, <strong>19%</strong> say home workers are <em>more</em> productive, and only <strong>13%</strong> see them as less productive (reference: <a href="https://www.theguardian.com/business/2025/mar/31/half-of-uk-professionals-might-quit-if-ordered-back-to-the-office-full-time-poll-shows">The Guardian</a>)</li><li>Multiple studies from the UK, Australia, and the US show no consistent productivity penalty for remote work, and in many cases, modest gains, when teams are well-managed (references: <a href="https://www.news.com.au/finance/work/at-work/burnout-underinvestment-to-blame-for-productivity-slump-not-working-from-home-aussie-academic/news-story/cfb0866fd6130b3b5c3b1f1b2ec628ad">News.com.au</a>, <a href="https://time.com/7296086/trumps-return-office-less-efficient">TIME</a>).</li></ul><p>Zooming in on software teams, a consistent pattern shows up: well-managed remote teams with clear goals, good documentation, and solid tooling perform at least as well as office-only teams, sometimes better (<a href="https://onlinelibrary.wiley.com/doi/10.1002/spe.3306">Wiley Online Library+1</a>). When remote “fails,” it’s usually because management, process, or culture failed, not because people weren’t sitting in the same building (<a href="https://www.microsoft.com/en-us/worklab/work-trend-index/hybrid-work">Microsoft Work Trend Index</a>)</p><h4>The way some bosses think we work from home:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*mPzbjGRciQvcblg4.gif" /></figure><h4>So… Back to the office? WFH?</h4><p>So is it economically logical to force everyone back to the office, especially in big, expensive cities, with long commutes and AI tools that don’t care where you sit?</p><p>Like almost 100% of things in life… <strong><em>It depends.</em></strong></p><ul><li>From a pure productivity + cost angle: often <strong>no</strong>.</li><li>From a politics, control, culture, and real estate angle: sometimes <strong>yes</strong>, which is why some big firms still push hard for RTO.</li></ul><p>The most robust pattern across research and surveys is this:</p><blockquote><strong>Flexibility beats dogma.</strong> Surveys of hybrid organisations show that <strong>teams with flexibility and agency</strong> (choosing remote, hybrid or office intentionally) tend to outperform organisations with rigid one-size-fits-all policies (reference: <a href="https://archieapp.co/blog/remote-work-statistics">archieapp.co</a>)</blockquote><h3>Will We All Be Forced Back to the Office?</h3><p>I don’t think so, not universally (oh, and I hope not 😅 at least not 100%, the rents in some big cities are simply insane if you want to have a family and a life… <em>We are not in the 1950s</em>)</p><p>What’s more likely:</p><ul><li><strong>Regulated, secret-heavy, or hardware-dependent work </strong>→ more in-office or hybrid (think defense, chips, on-prem financial systems).</li><li><strong>Pure software, cloud-native, product-driven teams </strong>→ remote-friendly or hybrid, especially when talent is global.</li><li><strong>High-status HQ cultures &amp; legacy leadership </strong>→ stronger push to be “seen” in person, even if the productivity data is fuzzy.</li></ul><p>For software engineers specifically, remote work is now a <em>baked-in expectation</em> for a big chunk of the talent pool. That Guardian poll? Almost <strong>half of UK professionals say they’d consider quitting</strong> if forced back to the office full-time (reference: <a href="https://www.theguardian.com/business/2025/mar/31/half-of-uk-professionals-might-quit-if-ordered-back-to-the-office-full-time-poll-shows">The Guardian</a>), <em>probably just bluff, but still, it is interesting!</em></p><p>Companies that ignore that trade talent for real-estate utilization. Some will decide it’s worth it. Others won’t. <strong><em>In the end, I’d like to say that we, the engineers, get to pick. By deciding where we take our talents?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*AG5yxvrhDUqewYQi.gif" /></figure><h3>How History Helps Us Predict the Future (Without LARPing as an Oracle)</h3><blockquote><strong>History doesn’t repeat, but it rhymes.</strong></blockquote><p>What we’ve seen with previous waves (industrialization, automation, computers, internet):</p><ol><li><strong>Tasks get automated before jobs do.</strong><br>We don’t “replace engineers”; we replace specific pieces of what engineers do.</li><li><strong>Demand for the <em>outcome</em> increases.</strong><br>When it gets cheaper to build software, people don’t build <em>less</em> of it.</li><li><strong>Skilled humans move up the abstraction ladder.</strong><br>From assembly to high-level languages. From on-prem servers to the cloud. From clicking deploy to owning SLOs and product metrics.</li></ol><p>So if we follow that pattern:</p><ul><li>AI will make coding cheaper → more software will be built.</li><li>Remote work will make talent more global → good engineers will have <em>more</em> options, not less (<strong><em>maybe a decrease in salary in some areas and an increase in others?</em></strong>)</li><li>The value will move toward <strong>system design, domain expertise, and human judgment.</strong></li></ul><p>That’s where you want to be.</p><h3>So… What Actually Happens to Our Jobs?</h3><p>With AI + remote work, here’s the shape of the future I’d bet on:</p><h4>1. Devs become more like architects and reviewers</h4><p>Not “enterprise ivory-tower architects” that never touch code, but:</p><ul><li><strong>Engineers who can design systems end-to-end.</strong></li><li><strong>People who can read AI-generated code and say:</strong> “This will fail under load,” or “This breaks GDPR,” or “This design locks us in.”</li></ul><p>The bottleneck becomes <strong>good taste, good judgement, and deep understanding</strong>, not typing speed.</p><h4>2. Productivity gains are real, but not 10×</h4><p>Real-world numbers so far suggest:</p><ul><li><strong>20–50% speed-ups</strong> on well-scoped programming tasks with AI (reference: <a href="https://resources.github.com/learn/pathways/copilot/essentials/measuring-the-impact-of-github-copilot">GitHub Resources+1</a>)</li><li><strong>Double-digit percentage gains</strong> in routine work when AI is integrated into the workflow (laptops, tooling, automation) (reference: <a href="https://www.delltechnologies.com/asset/en-us/products/laptops-and-2-in-1s/customer-stories-case-studies/deloitte-customer-case-study.pdf">Dell+1</a>)</li></ul><p>But these gains are:</p><ul><li>Fragmented across tasks.</li><li>Eaten by meetings, uncertainty, and rework if organizations don’t adapt (reference: <a href="https://www.itpro.com/software/development/atlassian-says-ai-has-created-an-unexpected-paradox-for-software-developers-theyre-saving-over-10-hours-a-week-but-theyre-still-overworked-and-losing-an-equal-amount-of-time-due-to-organizational-inefficiencies">IT Pro</a>)</li></ul><p><em>So: yes, management will want “more done with less and better.”</em><br>But no, you shouldn’t blindly chase 10× fantasies. You should optimize for <strong>sustainable high leverage</strong>, not burnout.</p><h4>3. Remote work + AI makes individual leverage explode</h4><p>A single strong engineer with:</p><ul><li>Deep system understanding</li><li>Strong communication</li><li>Good AI tooling skills</li><li>A remote setup that actually works</li></ul><p>…can create and maintain systems that used to need a small team.</p><p>This doesn’t mean “fewer jobs forever.” It means:</p><ul><li><strong>Weaker engineers get squeezed.</strong></li><li><strong>Strong generalists and deep specialists become absurdly valuable.</strong></li></ul><h3>Where to Place Your Bets (Fields That Will Be Harder to Automate Away)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*rkexrSMbFqlUqP19.gif" /></figure><p>No job is 100% safe (<em>but that was never true, for any job, ever. Even kings were not safe!… And oh boy, did they think they were.</em>). But some areas are clearly <strong>harder</strong> to fully automate in the near term because they require deep context, multi-disciplinary reasoning, or high-stakes judgment.</p><p>If you want to stay relevant, consider leaning into:</p><p><strong>1. System &amp; Cloud Architecture</strong></p><ul><li>Designing distributed systems under real constraints (latency, cost, compliance, failure).</li><li>Trade-offs between services, queues, storage, observability, and reliability.</li></ul><p><strong>2. Security &amp; Reliability (especially at scale)</strong></p><ul><li>Offensive and defensive security, threat modeling, and incident response.</li><li>SRE, chaos engineering, performance tuning, and designing for resilience.<br> (AI can suggest patches; it’s much harder for it to fully own responsibility for risk.)</li></ul><p><strong>3. Infrastructure, Tooling &amp; Developer Experience</strong></p><ul><li>Building the platforms that other devs (and AIs) build on top of.</li><li>CI/CD, test strategy, observability, internal tooling, and AI integration into workflows.</li></ul><p><strong>4. Domain-Heavy Product Engineering</strong></p><ul><li>Finance, healthcare, industrial systems, legal tech, deep B2B, where domain rules are messy, evolving, and partly unwritten.</li><li>The more human and regulatory context, the harder full automation becomes.</li></ul><p><strong>5. Leadership, Communication &amp; Coordination</strong></p><ul><li>Aligning teams, negotiating trade-offs with stakeholders, and balancing tech and business.</li><li>AI won’t replace humans as long as we still argue about roadmaps in meetings.</li></ul><p><strong>6. Human-Facing &amp; Trust-Heavy Roles</strong></p><ul><li>Consulting, technical pre-sales, client-facing architecture, education, mentoring.</li><li>Anywhere trust, empathy, and human nuance matter.</li></ul><p><strong>7. Or maybe something else entirely?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*hAG9EW9CMMf-Davw.gif" /></figure><h3>Actionable Steps to Stay Relevant (Today, Not in 2045)</h3><p>Here’s what I’m doing to remain relevant: maybe you can find something useful for yourself.</p><h4>1. Master AI as a tool, not a threat</h4><ul><li>Use AI daily: coding, tests, docs, explanations, refactors.</li><li>Learn its failure modes: hallucinations, shallow reasoning, security blind spots.</li><li>Treat it like a junior dev: helpful, fast, and absolutely needing review.</li></ul><h4>2. Go beyond syntax: learn systems and architecture</h4><ul><li>Study distributed systems, clean architecture, patterns like CQRS, event sourcing, and hexagonal architecture.</li><li>Practice designing systems from scratch: APIs, data models, scaling strategies, failure scenarios.</li></ul><h4>3. Get serious about remote work skills</h4><ul><li><strong><em>Asynchronous communication</em></strong> (clear written updates, solid PRs, useful documentation).</li><li><strong><em>Boundaries</em></strong>: when you’re online, when you go deep.</li><li><strong><em>Home setup</em></strong>: good audio, video, ergonomics. It sounds small, but it signals professionalism in a remote world.</li><li><strong><em>Time management</em></strong>: And yes, with “extra time” and nobody looking over your shoulder, it’s easy to procrastinate. That doesn’t help you or the rest of us. If too many of us coast, what do you think happens? We’ll get mass back-to-office mandates, and some of them will be deserved.</li><li>Remote work is an insane privilege: lunch with family, no soul-killing commute, fewer thousands spent on rent near city centres. We need to <em>earn </em>it by being organised, motivated, and grateful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*tMQiozm45U6oSn_w.gif" /></figure><h4>4. Build real things end-to-end</h4><ul><li>Side projects where you do: Idea → design → implementation → deployment → monitoring → iteration. <strong><em>You can do them faster with AI, so let’s do it! Who knows what we might build!</em></strong></li><li>This proves you can <strong>own outcomes</strong>, not just tickets.</li></ul><h4>5. Develop a “money sense.”</h4><ul><li>Understand how your work connects to revenue, cost, risk, or retention.</li><li>Ask “What’s the business impact?” as often as you ask “What’s the best pattern?”</li><li>And responsibly own your share.</li></ul><h4>6. Invest in human skills</h4><ul><li><strong><em>Writing</em></strong>: clear, concise, empathetic communication is an unfair advantage (even using AI, it is not so simple)</li><li><strong><em>Collaboration</em></strong>: be the engineer who can work with designers, PMs, sales, and legal.</li><li><strong><em>Teaching</em></strong>: if you can explain it simply, you understand it deeply (and you become harder to replace). I have a colleague who is the embodiment of this attribute, which makes him essential to our team and project.</li></ul><h4>7. Pick one depth lane</h4><p>Don’t just be “generic dev.” Aim to be:</p><ul><li><strong><em>The person for security in your org.</em></strong></li><li><strong><em>The person for performance and reliability.</em></strong></li><li><strong><em>The person for data modeling and consistency.</em></strong></li></ul><p><strong><em>Breadth + one serious depth</em></strong> is a very strong combination in an AI-augmented, remote-first world.</p><h3>Optimism Is Not Naive… It’s Strategic (right?)</h3><p>There’s no upside in fearing the future.</p><blockquote><strong>Fearing AI won’t stop it. Fearing remote work or back to the office mandates won’t change policy.</strong></blockquote><p>But understanding the <strong>direction of travel</strong> lets us surf the wave instead of being crushed by it.</p><ul><li>If AI stays an assistant → we write better, safer, cleaner software with less grunt work.</li><li>If AI becomes a fully-fledged engineer → we move up to vision, constraints, ethics, and design.</li><li>If remote wins → our talent market becomes global, and we compete on skill, not proximity (you can work from a beach sipping margaritas? Or simply save thousands a year on rent and live your dream life in the countryside? Or whatever you like.)</li><li>If RTO wins in some companies → others will exploit that by offering flexibility and scooping up talent (Less competition, but higher cost of living? You can potentially ask for more money or better perks?)</li></ul><p>In <em>every</em> scenario, three things stay valuable:</p><ol><li><strong>Understanding how systems actually work.</strong></li><li><strong>The ability to think clearly about trade-offs.</strong></li><li><strong>The courage to keep learning, even when the ground is moving.</strong></li></ol><p>So maybe the real questions aren’t:</p><blockquote>“Will AI replace us?” <br>“Will remote work flood the talent pool and weed me out?” <br>“Will I be forced back into a 5-day office commute just to keep my job?”</blockquote><p>A better question is:</p><blockquote><strong>“Who do I need to become so that AI and remote work make me more valuable, not less?”</strong></blockquote><p>And until we have a compiler for the future:</p><pre>// Final clause<br>throw new IKnowNothingException(&quot;The future isn’t yet defined, but it’s worth engineering.&quot;);</pre><p>Thank you for reading, see you in the next one</p><p><strong><em>Keep coding,<br>Marcelo</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed8f93e841b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Pattern, Part 2: What Spring Really Stores When It Creates Your Beans]]></title>
            <link>https://medium.com/@mregra-marcelo-silva/factory-pattern-part-2-what-spring-really-stores-when-it-creates-your-beans-9fa2e783762b?source=rss-f35fcd5cfe22------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa2e783762b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[MRegra]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 18:01:59 GMT</pubDate>
            <atom:updated>2025-11-13T18:01:59.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQdwJ-rRh9Yu1CaguvkYAw.png" /></figure><p>In the first part of this series, we built our way up from this:</p><pre>new StripeGateway();</pre><p>to this:</p><pre>@Autowired<br>PaymentGateway gateway;</pre><p>We started with plain new statements everywhere, then moved to a factory, built a tiny DIY dependency container, and finally let Spring take over with <strong><em>@Configuration</em></strong> and <strong><em>@Bean</em></strong>.</p><p>That gave us a clean setup where Spring magically provided a <strong><em>PaymentProcessor </em></strong>using either Stripe or PayPal, all driven by a simple configuration value.</p><p>After publishing that article, a very smart colleague of mine left a comment I absolutely loved:</p><blockquote><strong>“Hey Marcelo! Nice article, good job.<br>I have one comment tho, there is much and much more behind the scene of how Spring initialize and store beans. I was hoping that you going to tell something about BeanDefinition, </strong>BeanDefinitionRegistry <strong>and BeanPostProcessor. Maybe can be a good continuation for the part two? ;)”</strong></blockquote><p>Thank you for this amazing comment and suggestion!! That’s exactly what this post is about!</p><p><strong><em>In other words:</em></strong></p><blockquote>“Okay Spring, I know you’re a fancy factory. But <strong>what do you actually store inside, and when?</strong>”</blockquote><h3>TL;DR — What You’ll Learn</h3><p>By the end of this post, you’ll:</p><ul><li>Understand what a <strong><em>BeanDefinition </em></strong>actually is (hint: Spring stores <em>metadata</em>, not objects first).</li><li>See how <strong><em>BeanDefinitionRegistry </em></strong>works as the “catalog” of all those bean blueprints.</li><li>Use a <strong><em>BeanDefinitionRegistryPostProcessor </em></strong>to: Log all bean definitions.</li><li>Use a <strong><em>BeanPostProcessor </em></strong>to hook into the lifecycle of a real bean (<strong><em>PaymentProcessor</em></strong>) <em>as it’s being created</em>.</li><li>Connect all of this back to the mental model from Part 1 (factory → container → Spring).</li></ul><p>Let’s check things under the hood this time to make sense of this “magic”.</p><h3>Stage 0 — The Setup: Stripe, PayPal, and a Processor</h3><p>We’ll reuse the same example: a payment system with two gateways.</p><p><strong>Contract:</strong></p><pre>package org.factory.domain;<br><br>public interface PaymentGateway {<br>    void charge(double amount);<br>    String name();<br>}</pre><p>Implementations:</p><pre>package org.factory.domain;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class StripeGateway implements PaymentGateway {<br><br>    @Override<br>    public void charge(double amount) {<br>        log.info(&quot;[Stripe] Charging {}&quot;, amount);<br>    }<br><br>    @Override<br>    public String name() {<br>        return &quot;stripe&quot;;<br>    }<br>}</pre><pre>package org.factory.domain;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class PaypalGateway implements PaymentGateway {<br>    @Override<br>    public void charge(double amount) {<br>        log.info(&quot;[PayPal] Charging {}&quot;, amount);<br>    }<br>    @Override<br>    public String name() {<br>        return &quot;paypal&quot;;<br>    }<br>}</pre><p>Consumer:</p><pre>package org.factory.domain;<br><br>import lombok.Getter;<br>import lombok.extern.slf4j.Slf4j;<br><br>@Getter<br>@Slf4j<br>public class PaymentProcessor {<br>    private final PaymentGateway gateway;<br><br>    public PaymentProcessor(PaymentGateway gateway) {<br>        this.gateway = gateway;<br>    }<br><br>    public void process(double amount) {<br>        log.info(&quot;Using gateway: {}&quot;, gateway.name());<br>        gateway.charge(amount);<br>    }<br>}</pre><p>So far, nothing Spring-specific. We just have:</p><ul><li>An interface (<strong><em>PaymentGateway</em></strong>)</li><li>Two implementations (<strong><em>StripeGateway</em></strong>, <strong><em>PaypalGateway</em></strong>)</li><li>A class that depends on the interface (<strong><em>PaymentProcessor</em></strong>)</li></ul><p>This is the same story as Part 1, with Lombok and logging.</p><h3>Stage 1 — Let Spring Handle the Wiring (and Choose a Default)</h3><p>In Part 1, we saw how Spring makes this kind of wiring declarative.</p><p>Let’s do the same here, but with one important twist: <strong>configuration decides</strong> whether we use Stripe or PayPal.</p><p>First, a tiny enum:</p><pre>package org.manuaway.factory.config;<br><br>public enum GatewayType { STRIPE, PAYPAL }</pre><p>Now, the configuration class:</p><pre>package org.manuaway.factory.config;<br><br>import org.manuaway.factory.domain.PaymentGateway;<br>import org.manuaway.factory.domain.PaymentProcessor;<br>import org.manuaway.factory.domain.PaypalGateway;<br>import org.manuaway.factory.domain.StripeGateway;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>/**<br> * In Spring, @Bean methods are factory methods.<br> * The container calls these to create and wire our objects.<br> */<br>@Configuration<br>public class PaymentConfig {<br><br>    @Bean<br>    public PaymentGateway paymentGateway(<br>            @Value(&quot;${payment.gateway:STRIPE}&quot;) GatewayType type<br>    ) {<br>        return switch (type) {<br>            case PAYPAL -&gt; new PaypalGateway();<br>            case STRIPE -&gt; new StripeGateway();<br>        };<br>    }<br><br>    /**<br>     * Factory method for PaymentProcessor.<br>     * Spring calls it automatically during startup when it builds the ApplicationContext.<br>     */<br>    @Bean<br>    public PaymentProcessor paymentProcessor(PaymentGateway gateway) {<br>        return new PaymentProcessor(gateway);<br>    }<br>}</pre><p>A few important points:</p><ul><li><strong><em>@Configuration</em></strong> tells Spring: “<strong><em>This class contains bean factory methods.</em></strong>”</li><li>Each <strong><em>@Bean</em></strong> method is a <strong>factory method</strong>.</li><li><strong><em>paymentGateway(…)</em></strong> reads a property (<strong><em>payment.gateway</em></strong>) and chooses the implementation.</li><li><strong><em>paymentProcessor(PaymentGateway gateway)</em></strong> uses constructor injection:</li><li>Spring looks for a bean of type <strong><em>PaymentGateway</em></strong></li><li>It finds the one we just defined</li><li>It calls the constructor and wires everything up</li></ul><p>With a simple Spring Boot app:</p><pre>package org.manuaway.factory;<br><br>import org.manuaway.factory.domain.PaymentProcessor;<br>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.context.annotation.Bean;<br><br>@SpringBootApplication<br>public class Main {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Main.class, args);<br>    }<br><br>    // Runner executes after Spring finishes startup<br>    @Bean<br>    public CommandLineRunner run(PaymentProcessor processor) {<br>        return args -&gt; processor.process(49.99);<br>    }<br>}</pre><p>And this property:</p><pre># application.properties<br>payment.gateway=STRIPE<br># or<br># payment.gateway=PAYPAL</pre><p>When we run the app, we’ll see either:</p><ul><li>Stripe logs, or</li><li>PayPal logs, depending on that single config key.</li></ul><p>So far, this is “normal Spring”:</p><ul><li>We declare beans.</li><li>Spring wires them.</li><li>Config decides behaviour.</li></ul><p>Now let’s peel back the magic.</p><h3>Stage 2 — BeanDefinition: Spring Stores Recipes, Not Objects</h3><p>Here’s a key idea:</p><blockquote>Spring doesn’t start by creating all our beans.<br>It starts by creating <strong>descriptions</strong> of our beans.</blockquote><p>Those descriptions are <strong><em>BeanDefinition </em></strong>objects.</p><p>A <strong><em>BeanDefinition </em></strong>is basically a set of instructions, or a recipe, that tells Spring how to create a bean when needed.<br>Each one contains things like:</p><ul><li>The bean’s class (or factory method)</li><li>Scope (singleton, prototype, etc.)</li><li>Whether it’s lazy or eager</li><li>Autowire mode</li><li>Constructor arguments and property values</li><li>A bunch of other metadata and flags</li></ul><p>Think of it this way:</p><blockquote>Spring collects all our recipes first, and only later starts cooking.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*zUTzFu9TMpWtnqhSfSsOKg.gif" /></figure><p>Let’s prove that by writing a small component that prints some of those bean recipes before Spring starts instantiating anything.</p><pre>package org.manuaway.factory.beans;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.BeansException;<br>import org.springframework.beans.factory.config.BeanDefinition;<br>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;<br>import org.springframework.beans.factory.support.BeanDefinitionRegistry;<br>import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Arrays;<br>import java.util.Set;<br><br>@Slf4j<br>@Component<br>public class BeanDefinitionLogger implements BeanDefinitionRegistryPostProcessor {<br><br>    private static final String ROOT_PACKAGE = &quot;org.manuaway.factory&quot;;<br>    private static final Set&lt;String&gt; IMPORTANT_BEAN_NAMES = Set.of(<br>            &quot;paymentConfig&quot;,<br>            &quot;paymentGateway&quot;,<br>            &quot;paymentProcessor&quot;<br>    );<br><br>    @Override<br>    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)<br>            throws BeansException {<br><br>        log.info(&quot;=== [BeanDefinitionRegistry] Selected bean definitions ===&quot;);<br><br>        Arrays.stream(registry.getBeanDefinitionNames())<br>                .sorted()<br>                .forEach(name -&gt; {<br>                    BeanDefinition bd = registry.getBeanDefinition(name);<br>                    String className = bd.getBeanClassName();<br><br>                    if (!shouldLogBean(name, className)) {<br>                        return;<br>                    }<br><br>                    String scope = (bd.getScope() == null || bd.getScope().isEmpty())<br>                            ? &quot;singleton&quot;<br>                            : bd.getScope();<br><br>                    log.info(&quot;beanName={}, class={}, scope={}, lazyInit={}&quot;,<br>                            name, className, scope, bd.isLazyInit());<br>                });<br>    }<br><br>    private boolean shouldLogBean(String beanName, String className) {<br>        // Always log the key beans for this example<br>        if (IMPORTANT_BEAN_NAMES.contains(beanName)) {<br>            return true;<br>        }<br>        // Also log any bean whose class is in *our* packages<br>        return className != null &amp;&amp; className.startsWith(ROOT_PACKAGE);<br>    }<br><br>    @Override<br>    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)<br>            throws BeansException {<br>        // nothing for now<br>    }<br>}</pre><p><strong><em>What’s going on here?</em></strong></p><ul><li><strong><em>BeanDefinitionRegistryPostProcessor </em></strong>is a special hook that Spring calls <strong>very early</strong> in the startup process.</li></ul><p><strong>At this point:</strong></p><ul><li>All <strong><em>BeanDefinitions </em></strong>have been registered.</li><li>But <strong>no beans have been instantiated yet</strong>.</li><li>We get access to the <strong><em>BeanDefinitionRegistry</em></strong>: This is the internal registry where Spring keeps all <strong><em>{ beanName → BeanDefinition }</em></strong> entries.</li></ul><p>Our logger simply loops through them, filters to the ones in our package (plus a few key ones), and prints out their metadata.</p><h4>Example output (simplified)</h4><pre>=== [BeanDefinitionRegistry] Selected bean definitions ===<br>beanName=<strong>paymentConfig</strong>, class=org.factory.config.PaymentConfig, scope=singleton, lazyInit=false<br>beanName=<strong>paymentGateway</strong>, class=null, scope=singleton, lazyInit=false<br>beanName=<strong>paymentProcessor</strong>, class=null, scope=singleton, lazyInit=false<br>...</pre><p>The moment I saw the logs… It was like a small “eureka” moment, and I thought: “There you are!”.</p><p>Then later in the startup logs:</p><pre>Tomcat initialized with port 8080 (http)<br>Starting service [Tomcat]<br>Starting Servlet engine: [Apache Tomcat/10.1.46]<br>Initializing Spring embedded WebApplicationContext<br>Root WebApplicationContext: initialization completed in 978 ms<br><strong>[BeanPostProcessor] Before init: paymentProcessor (PaymentProcessor)<br>[BeanPostProcessor] After init: paymentProcessor (PaymentProcessor)</strong><br>Started Main in 1.872 seconds (process running for 2.213)<br><strong>Using gateway: stripe<br>[Stripe] Charging 49.99</strong></pre><h4>Things to notice</h4><ul><li><strong><em>paymentConfig </em></strong>appears as a bean; it’s our <strong><em>@Configuration</em></strong> class.</li><li>Some <strong><em>class </em></strong>values are <strong><em>null </em></strong>because those beans come from factory methods (<strong><em>@Bean</em></strong> methods). Spring knows how to build them, but their definitions don’t point directly to a concrete class.</li></ul><h4><strong>Key takeaway:</strong></h4><blockquote>Before <strong>PaymentProcessor </strong>ever exists as a Java object, Spring has a <strong>BeanDefinition </strong>describing how to create it.</blockquote><p>That’s essentially the internal version of the “factory configuration” we wrote by hand back in Part 1.</p><h3>Stage 3 — BeanPostProcessor: Intercepting Real Objects</h3><p>So far, everything we did was at the <strong>metadata level</strong>:</p><ul><li><strong><em>BeanDefinition </em></strong>→ recipe.</li><li><strong><em>BeanDefinitionRegistry </em></strong>→ registry of recipes.</li><li><strong><em>BeanDefinitionRegistryPostProcessor </em></strong>→ a hook to inspect (or modify) recipes <em>before </em>beans are created.</li></ul><p>Now we’ll move a level down.</p><p>What if you want to intercept <strong>actual bean instances,</strong><em> the real objects</em><strong>, </strong>as they are being created?</p><blockquote>That’s where <strong><em>BeanPostProcessor </em></strong>comes in.</blockquote><p>We’ll create one that traces the lifecycle of <strong><em>PaymentProcessor</em></strong>:</p><pre>package org.manuaway.factory.beans;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.manuaway.factory.domain.PaymentProcessor;<br>import org.springframework.beans.BeansException;<br>import org.springframework.beans.factory.config.BeanPostProcessor;<br>import org.springframework.stereotype.Component;<br><br>@Slf4j<br>@Component<br>public class TracingBeanPostProcessor implements BeanPostProcessor {<br><br>    @Override<br>    public Object postProcessBeforeInitialization(Object bean, String beanName)<br>            throws BeansException {<br><br>        if (bean instanceof PaymentProcessor) {<br>            log.info(&quot;[BeanPostProcessor] Before init: {} ({})&quot;,<br>                    beanName, bean.getClass().getSimpleName());<br>        }<br>        return bean;<br>    }<br><br>    @Override<br>    public Object postProcessAfterInitialization(Object bean, String beanName)<br>            throws BeansException {<br><br>        if (bean instanceof PaymentProcessor) {<br>            log.info(&quot;[BeanPostProcessor] After init: {} ({})&quot;,<br>                    beanName, bean.getClass().getSimpleName());<br>        }<br>        return bean;<br>    }<br>}</pre><h4>What’s happening here?</h4><p>The <strong><em>BeanPostProcessor </em></strong>interface lets you run code around bean initialization.</p><p>Specifically:</p><ul><li><strong><em>postProcessBeforeInitialization </em></strong>runs <strong>after the bean has been constructed</strong>, but <strong>before</strong> any <strong><em>@PostConstruct</em></strong> or initialization callbacks.</li><li><strong><em>postProcessAfterInitialization </em></strong>runs <strong>after</strong> initialization, right before the bean is returned to the container.</li></ul><p>In our example, we’re only interested in one specific bean:</p><pre>if (bean instanceof PaymentProcessor) { ... }</pre><p>That way, we trace its lifecycle without cluttering the logs for every bean in the application.</p><h4>Example output</h4><p>When you run the app now, you’ll see logs like:</p><pre>[BeanPostProcessor] Before init: paymentProcessor (PaymentProcessor)<br>[BeanPostProcessor] After init: paymentProcessor (PaymentProcessor)<br>Using gateway: stripe<br>[Stripe] Charging 49.99</pre><p>(if <strong><em>payment.gateway=STRIPE</em></strong>), or the PayPal equivalent.</p><h4><strong>Key idea:</strong></h4><ul><li><strong><em>BeanDefinitionRegistryPostProcessor</em></strong> works with <strong>definitions</strong> <em>before</em> instantiation, meaning before beans exist.</li><li><strong><em>BeanPostProcessor </em></strong>works with <strong>instances</strong> <em>around</em> initialization, meaning once the beans are being initialized.</li></ul><p>This is the mechanism behind a lot of Spring “magic”:</p><ul><li><strong><em>@Transactional proxies</em></strong></li><li><strong><em>@Async</em></strong></li><li><strong><em>AOP</em></strong></li><li><strong><em>Validation hooks</em></strong></li></ul><p>They are essentially “fancy” <strong><em>BeanPostProcessor </em></strong>wrapping or modifying your beans as they come out of the factory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*ODGeAhX3X7eymUOZaZi6Pg.gif" /><figcaption><strong>Charlie Chaplin</strong> as the “BeanPostProcessor”</figcaption></figure><h3>Stage 4 — Connecting Part 1 and Part 2</h3><p>Let’s connect this back to where we started.</p><h4>In Part 1, we built:</h4><ul><li>A simple <strong>Factory</strong> (<strong><em>PaymentGatewayFactory</em></strong>)</li><li>A tiny <strong>container</strong> that manages singletons. Did constructor injection. Delegated special cases to the factory.</li></ul><p><strong>We manually implemented:</strong></p><ol><li><em>What</em> to create.</li><li><em>How</em> to wire objects together.</li><li><em>Who</em> owns the lifecycle, and when they are created.</li></ol><p>Then we replaced that DI container with Spring’s <strong><em>ApplicationContext</em></strong>.</p><h4>In Part 2, you saw what Spring does inside that container:</h4><ol><li><strong>Parse configuration:</strong><br>→ Reads <strong><em>@Configuration</em></strong>, <strong><em>@Bean</em></strong>, <strong><em>@Component</em></strong>, etc.</li><li><strong>Create <em>BeanDefinitions</em></strong><br>→ For each bean, builds a metadata recipe (class, scope, lazy, constructor args, …).</li><li><strong>Stores them in a <em>BeanDefinitionRegistry</em></strong><br>→ Essentially a big internal map of <strong><em>{ beanName → BeanDefinition }</em></strong>.</li><li><strong>Let&#39;s inspect them</strong><br>→ Using a <strong><em>BeanDefinitionRegistryPostProcessor </em></strong>(<strong><em>BeanDefinitionLogger </em></strong>in our example).</li><li><strong>Instantiate beans</strong><br>→ Using those definitions, in the right order, resolving dependencies.</li><li><strong>Wrap and customize instances</strong><br>→ Using <strong><em>BeanPostProcessor </em></strong>(our <strong><em>TracingBeanPostProcessor</em></strong>), which adds extra logic.</li><li><strong>Exposes fully wired beans</strong><br><strong><em> </em></strong>→ So <strong><em>ApplicationContext.getBean(PaymentProcessor.class)</em></strong> just returns a ready-to-use <strong><em>PaymentProcessor </em></strong>that already has the correct <strong><em>PaymentGateway</em></strong> injected.</li></ol><p>So the question from Part 1:</p><blockquote>“Where is the logic that chooses Stripe or PayPal?”</blockquote><p>Now has multiple layers of answers:</p><ul><li><strong>High level: </strong>In our <strong><em>@Configuration</em></strong> class + <strong><em>payment.gateway</em></strong> property.</li><li><strong>Under the hood: </strong>In the <strong><em>BeanDefinition, </em></strong>Spring builds from that configuration.</li><li><strong>Registry level: </strong>In the entries stored inside the <strong><em>BeanDefinitionRegistry</em></strong>.</li><li><strong>Runtime level: </strong>In what <strong><em>BeanPostProcessors </em></strong>do to your beans after they’re created.</li></ul><h3>When Should You Care About This? (Real-World Applications, kinda)</h3><p>Most of the time, I (<em>we?</em>) don’t need to.</p><p>You can happily live at the:</p><ul><li><strong><em>@Service</em></strong></li><li><strong><em>@Component</em></strong></li><li><strong><em>@Configuration</em></strong></li><li><strong><em>@Bean</em></strong></li></ul><p>level and never touch <strong><em>BeanDefinition </em></strong>manually.</p><p><strong>But knowing what happens underneath becomes really useful when (or, at the very least, is fun to know, I’d say):</strong></p><ul><li><strong><em>Building libraries or frameworks on top of Spring</em></strong>: where you might want to register beans dynamically or modify how others are created.</li><li><strong><em>Auto-registering beans</em></strong> based on annotations, packages, or classpath scanning.</li><li><strong><em>Debugging tricky behavior</em></strong> and asking questions like: “What beans are actually registered?”. “What’s wrapping my bean before it reaches me?”</li><li><strong><em>Deepening your mental model: </em></strong>so that <strong><em>@Autowired</em></strong> and <strong><em>@Bean</em></strong> stop feeling magical and start feeling mechanical.</li></ul><p>It’s like understanding how your car engine works; you don’t need it to drive, but once you know, every sound and hiccup makes a lot more sense.</p><h3>Summary</h3><p>In Part 2, we:</p><ul><li>Used the same <strong>Stripe vs PayPal</strong> scenario as Part 1.</li><li>Let Spring wire <strong><em>PaymentProcessor </em></strong>with <strong><em>@Configuration</em></strong> and <strong><em>@Bean</em></strong>.</li><li>Introduced some key players:<br>→ <strong><em>BeanDefinition </em></strong>– the internal description of each bean.<br>→ <strong><em>BeanDefinitionRegistry </em></strong>– where those descriptions are stored.<br>→ <strong><em>BeanDefinitionRegistryPostProcessor </em></strong>– a hook to inspect and modify bean definitions before instantiation.<br>→ <strong><em>BeanPostProcessor </em></strong>– a hook to intercept real instances around initialization.</li><li>Dynamically registered a <strong><em>paypalGateway </em></strong>bean <strong>without</strong> a <strong><em>@Bean</em></strong> or <strong><em>@Component</em></strong>.</li></ul><p>So now when you see:</p><pre>@Autowired<br>PaymentGateway gateway;</pre><p>You can mentally picture the whole path:</p><blockquote><strong>@Bean</strong> → <strong>BeanDefinition </strong>→ <strong><em>BeanDefinitionRegistry </em></strong>→ (registry post-processors) → instantiate → (bean post-processors) → injected into your class.</blockquote><p>The magic is still there… but now you know the machinery behind it.</p><h3>Final Thoughts</h3><p>For those who are amazing enough to be here still, reading this, I am truly thankful; it is for you that I write this. Thanks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*Lp14XldfqYvasUCnn4-vJQ.gif" /></figure><p>It’s been a really fun ride learning all of this. I had some vague idea of <strong><em>BeanDefinition</em> </strong>and <strong><em>BeanPostProcessor </em></strong>before, but challenging myself to wire a real example, run it, and log what’s going on made everything clear. There was a lot to learn, and I’m genuinely glad I took the time to better understand this topic. I hope this post helped you connect a few dots, too.</p><p>I have plenty more interesting things in my backlog, from DevSecOps to Software Engineering, Software Architecture, Observability, Infra, etc! And I’m always open to suggestions you might have! Join me on this journey, you are very welcome!</p><h3>The code!</h3><p>Organized by learning stage:</p><ul><li><strong>manual-way-simple</strong> → naïve, <strong><em>new</em></strong></li><li><strong>manual-way</strong> → factory + mini DI container</li><li><strong>spring-way</strong> → <strong><em>@Bean</em></strong> factories, enum/profiles, and conditional beans</li><li><strong><em>(NEW!)</em> spring-advanced</strong> → <strong><em>@BeanDefinition</em></strong>, <strong><em>BeanPostProcessor</em></strong>, <strong><em>BeanDefinitionRegistry</em></strong>, among other, more in-depth characteristics of spring bean creation mechanisms.</li></ul><p>You can find the code for all of this in this <a href="https://github.com/MRegra/factory-pattern-medium-post">repo</a>. If you have any feedback or questions, please don’t hesitate to let me know in the comments.</p><p>Thank you for reading, see you in the next one</p><p><strong><em>Cheers,</em></strong></p><p><strong><em>Marcelo</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa2e783762b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Pattern: “How Spring Creates Your Beans”]]></title>
            <link>https://medium.com/@mregra-marcelo-silva/factory-pattern-how-spring-creates-your-beans-0898bda4c7d4?source=rss-f35fcd5cfe22------2</link>
            <guid isPermaLink="false">https://medium.com/p/0898bda4c7d4</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[MRegra]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 18:01:55 GMT</pubDate>
            <atom:updated>2025-11-05T18:01:55.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PbXNpeRWzMQLZFt9zBOrA.png" /></figure><p>Spring makes everything look so clean that we often forget how much machinery runs behind a single <strong>@Bean.</strong></p><p>Imagine this, you’re working on a payment system. Your client suddenly decides:</p><blockquote>Hey, we need to support both Stripe and PayPal.</blockquote><p>You roll your eyes. You know what that means:</p><pre>if (gateway.equals(&quot;stripe&quot;)) { <br>  new StripeGateway(); <br>} else { <br>  new PaypalGateway(); <br>}</pre><p><strong>Everywhere.</strong></p><p>It’s fine for one method… until you have <strong>dozens</strong> of classes doing the same thing. Now you’re debugging brittle code scattered all over your system.</p><p>Then you see a codebase using Spring. No factories. No <strong><em>if/else</em></strong>. Just:</p><pre>@Autowired PaymentGateway gateway;</pre><p>And everything <em>works</em>.</p><p>You think:</p><blockquote>“Wait! Where is the logic that chooses Stripe or PayPal?”</blockquote><p>That’s the rabbit hole we’re going down today.</p><h3>TL;DR: What You’ll Learn</h3><p>By the end of this post, you’ll be able to:</p><ul><li>Understand why the <strong>Factory Pattern</strong> exists, and when to use it.</li><li>See how <strong>Dependency Injection</strong> emerges naturally from it.</li><li>Build it manually (in plain Java).</li><li>Create a <strong>tiny version of Spring’s ApplicationContext</strong>.</li><li>Then, finally, see how <strong>Spring Boot abstracts it all away</strong> using <strong><em>@Configuration</em></strong> and <strong><em>@Bean</em></strong>.</li></ul><p>You’ll <em>build the magic</em> manually, then see how Spring abstracts it away.</p><h3>Stage 1: The Manual (not so smart) way, A.K.A “new” Everything</h3><p>At first, your code looks clean:</p><pre>// Contract<br>public interface PaymentGateway {<br>    void charge(double amount);<br>    String name();<br>}<br><br>// Implementations<br>public class StripeGateway implements PaymentGateway {<br>    public void charge(double amount) { <br>      System.out.println(&quot;[Stripe] Charging &quot; + amount); <br>    }<br>    public String name() { <br>      return &quot;stripe&quot;; <br>    }<br>}<br><br>public class PaypalGateway implements PaymentGateway {<br>    public void charge(double amount) { <br>      System.out.println(&quot;[PayPal] Charging &quot; + amount); <br>    }<br>    public String name() { <br>      return &quot;paypal&quot;; <br>    }<br>}<br><br>// Consumer<br>public class PaymentProcessor {<br>    private final PaymentGateway gateway;<br>    public PaymentProcessor(PaymentGateway gateway) { <br>      this.gateway = gateway; <br>    }<br>    public void process(double amount) {<br>        System.out.println(&quot;Using gateway: &quot; + gateway.name());<br>        gateway.charge(amount);<br>    }<br>}<br><br>// Main<br>public class Main {<br>    public static void main(String[] args) {<br>        PaymentGateway gw = new StripeGateway(); // or new PaypalGateway()<br>        new PaymentProcessor(gw).process(49.99);<br>    }<br>}</pre><p>It works fine until requirements change… Now your PM says:</p><blockquote>“We’re switching to (or adding) PayPal.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*nDALkdcfiNifQn9M98SsZQ.gif" /></figure><p>And you realize your system has <strong>12 places</strong> hardcoding <strong><em>new StripeGateway()</em></strong>. That’s one way to practice your typing skills. 🤣</p><p><strong>Welcome to <em>tight coupling</em>.</strong></p><h4>These are the first pain points:</h4><ul><li>Creation logic is duplicated</li><li>Switching implementations requires code edits</li><li>Harder to test (you always instantiate real objects)</li></ul><blockquote><strong><em>FYI:</em> This design is intentionally painful. It sets up the “why” for factories and DI.</strong></blockquote><h3>Stage 2 — Building the Factory Pattern by Hand!</h3><p>Let’s fix this mess using the <strong>Factory Design Pattern</strong>.</p><p>Instead of hardcoding <strong><em>new StripeGateway()</em></strong> everywhere, you’ll centralize creation logic:</p><pre>public class PaymentGatewayFactory {<br>    private final Properties props;<br><br>    public PaymentGatewayFactory(Properties props) {<br>        this.props = props;<br>    }<br><br>    public PaymentGateway create() {<br>        String type = props.getProperty(&quot;payment.gateway&quot;, &quot;stripe&quot;).toLowerCase();<br>        return switch (type) {<br>            case &quot;paypal&quot; -&gt; new PaypalGateway();<br>            default       -&gt; new StripeGateway();<br>        };<br>    }<br>}</pre><p>Use it:</p><pre>Properties props = new Properties();<br>props.setProperty(&quot;payment.gateway&quot;, &quot;paypal&quot;);<br>PaymentGatewayFactory factory = new PaymentGatewayFactory(props);<br><br>PaymentProcessor processor = new PaymentProcessor(factory.create());<br>processor.process(49.99);</pre><p>Now configuration drives behavior:</p><pre>payment.gateway=stripe</pre><p>You can flip <strong>Stripe ↔ PayPal</strong> with one property. No refactors, no redeploys.</p><h4>The Factory Pattern</h4><blockquote>The Factory Pattern provides an interface for creating objects, letting subclasses or configurations decide which class to instantiate.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m3_ghGpBIR-gnTzr9_iTg.png" /><figcaption><strong>Image 1:</strong> PaymentProcessor → (requests) → PaymentGatewayFactory → returns either StripeGateway or PaypalGateway</figcaption></figure><p>It’s one of the most widely used <strong>creational patterns</strong>, and it’s the foundation of <strong>Dependency Injection (DI)</strong>.</p><p>It reduces coupling and centralizes decisions, the first step toward DI (Dependency Injection).</p><h4>Adding a Processor (Dependency Injection by Hand)</h4><pre>public class PaymentProcessor {<br>    private final PaymentGateway gateway;<br><br>    public PaymentProcessor(PaymentGateway gateway) {<br>        this.gateway = gateway;<br>    }<br><br>    public void process(double amount) {<br>        System.out.println(&quot;Using gateway: &quot; + gateway.name());<br>        gateway.charge(amount);<br>    }<br>}</pre><p>And the <strong><em>main()</em></strong>:</p><pre>Properties props = new Properties();<br>props.setProperty(&quot;payment.gateway&quot;, &quot;paypal&quot;);<br>PaymentGatewayFactory factory = new PaymentGatewayFactory(props);<br><br>PaymentProcessor processor = new PaymentProcessor(factory.create());<br>processor.process(49.99);</pre><p>We just performed <strong>manual dependency injection</strong>. But you’ll quickly hit a new problem… as soon as your graph grows, <em>you</em> are now the container. You’re responsible for wiring order, singletons, choosing implementations per environment, passing config around, and keeping tests painless. That gets messy fast.</p><p><strong>Solution:</strong> build a <em>tiny</em> DI container that handles constructor injection and singletons, and delegates special cases to a factory. In other words, take one step toward what Spring does for you.</p><h4>A Tiny DI Container (Constructor Injection + Singletons)</h4><p>Let’s go one step deeper and build a miniature ApplicationContext.<br>It should:</p><ul><li>keep a singleton registry</li><li>do constructor injection (a DI container typically chooses the <strong>constructor with the most dependencies</strong>)</li><li>delegate “special cases” to a factory (e.g., for interfaces)</li></ul><p>Sketch:</p><pre>public class MyApplicationContext {<br>    private final Map&lt;Class&lt;?&gt;, Object&gt; singletons = new HashMap&lt;&gt;();<br>    private final Map&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; customSuppliers = new HashMap&lt;&gt;();<br><br>    public &lt;T&gt; void registerBean(Class&lt;T&gt; type) { /* store type */ }<br>    public &lt;T&gt; void registerBean(Class&lt;T&gt; type, Supplier&lt;T&gt; supplier) {<br>        customSuppliers.put(type, supplier);<br>    }<br><br>    @SuppressWarnings(&quot;unchecked&quot;)<br>    public &lt;T&gt; T getBean(Class&lt;T&gt; type) {<br>        if (singletons.containsKey(type)) return (T) singletons.get(type);<br>        T instance = create(type);<br>        singletons.put(type, instance);<br>        return instance;<br>    }<br><br>    private &lt;T&gt; T create(Class&lt;T&gt; type) {<br>        // if custom supplier exists, use it<br>        // else pick the longest ctor, resolve params recursively, and new up<br>        // (error handling omitted for brevity)<br>    }<br>}</pre><p>Register and go:</p><pre>Config ctx = new MyApplicationContext();<br>ctx.registerBean(PaymentProcessor.class);<br>ctx.registerBean(PaymentGateway.class, () -&gt; new PaymentGatewayFactory(props).create());<br><br>PaymentProcessor p = ctx.getBean(PaymentProcessor.class);<br>p.process(49.99);</pre><p>You just built:</p><ul><li>centralized creation (Factory)</li><li>constructor injection (Container)</li><li>singletons (Lifecycle)</li></ul><blockquote>This is the <strong>mental model</strong> behind Spring. Now let’s replace your DIY container with the real thing.</blockquote><h3>Stage 3: The Problem of Scale</h3><p>Your application grows. Now each class has dependencies, and those dependencies have dependencies.</p><p>You’re juggling singletons, lifecycle management, and construction orders.</p><p>Suddenly, your main looks like a <strong>dependency jungle</strong>:</p><pre>Config config = new Config(&quot;app.properties&quot;);<br>MyApplicationContext ctx = new MyApplicationContext(config);<br>ctx.registerBean(PaymentProcessor.class);<br>ctx.registerBean(PaymentGateway.class);<br>PaymentProcessor processor = ctx.getBean(PaymentProcessor.class);</pre><p>You realize you’re <strong>reinventing a framework</strong>. And that’s exactly what Spring was built to solve.</p><h3>Stage 4: The Spring-Way — Declarative Dependency Injection</h3><p>Spring takes your factory idea and turns it into a <strong>declarative configuration</strong>:</p><pre>@Configuration<br>public class PaymentConfig {<br>    @Bean<br>    public PaymentGateway paymentGateway(@Value(&quot;${payment.gateway:stripe}&quot;) String type) {<br>        return switch (type.toLowerCase()) {<br>            case &quot;paypal&quot; -&gt; new PaypalGateway();<br>            default       -&gt; new StripeGateway();<br>        };<br>    }<br><br>    @Bean<br>    public PaymentProcessor paymentProcessor(PaymentGateway gateway) {<br>        return new PaymentProcessor(gateway);<br>    }<br>}</pre><p>Spring’s <strong><em>ApplicationContext </em></strong>now calls these factory methods <strong>automatically</strong> — creating, caching, and wiring your objects.</p><p>Your new <strong><em>Main </em></strong>class becomes beautifully simple:</p><pre>@SpringBootApplication<br>public class Main {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Main.class, args);<br>    }<br><br>    @Bean<br>    CommandLineRunner run(PaymentProcessor processor) {<br>        return args -&gt; processor.process(49.99);<br>    }<br>}</pre><p>Set configuration:</p><pre>payment.gateway=stripe</pre><p>Override at runtime:</p><pre>mvn -q spring-boot:run -Dspring-boot.run.arguments=&quot;--payment.gateway=paypal&quot;<br># or<br>java -jar app.jar --payment.gateway=paypal</pre><h3>What just happened?</h3><ul><li>Each <strong><em>@Bean</em></strong> method is a <strong>factory function</strong>.</li><li>Spring calls these on startup and registers the results.</li><li>Dependencies (method parameters) are <strong>injected</strong> automatically.</li><li>Beans are <strong>singletons</strong> by default.</li></ul><p>We’ve replaced your tiny container with a mature one that handles:</p><ul><li>lifecycle, scopes, conditions, profiles</li><li>property binding, test slices, auto-config</li></ul><h3>“Where Did My Factory Go?”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*gCbgp42sazqv8BU6qV-EcQ.gif" /></figure><p>It’s still there — <strong>hidden inside Spring’s core</strong>. Each <strong><em>@Bean</em></strong> method is, in fact, a <strong>factory method</strong>.</p><p>Spring detects these methods, calls them at startup, and registers their outputs in a global container. It also ensures you only get <strong>one instance per context</strong> (singleton by default).</p><p>So your manual logic:</p><pre>main() → factory → gateway → processor</pre><p>becomes this:</p><pre>ApplicationContext → calls @Bean → wires dependencies → provides ready-to-use objects</pre><h3>Smarter Factories: Beans + Profiles</h3><p>Sometimes, you want flexibility; for example, you might later add a profile-based configuration. Spring offers this:</p><pre>@Bean<br>@ConditionalOnMissingBean(PaymentGateway.class)<br>public PaymentGateway paymentGateway(@Value(&quot;${payment.gateway:STRIPE}&quot;) GatewayType type) {<br>    return switch (type) {<br>        case PAYPAL -&gt; new PaypalGateway();<br>        case STRIPE -&gt; new StripeGateway();<br>    };<br>}</pre><p><strong><em>@ConditionalOnMissingBean</em></strong> means:</p><blockquote>“Only register this bean if no other bean of this type exists.”</blockquote><p>This lets you add <strong>overrides or profiles</strong> later — without breaking the default setup.</p><pre>@Configuration<br>public class PaymentConfigProfiles {<br>    @Bean @Profile(&quot;stripe&quot;) public PaymentGateway stripe() { <br>      return new StripeGateway(); <br>    }<br>    @Bean @Profile(&quot;paypal&quot;) public PaymentGateway paypal() { <br>      return new PaypalGateway(); <br>    }<br>}</pre><p>Now switching environments or frameworks becomes trivial — just set:</p><pre>--spring.profiles.active=paypal</pre><h3>Stage 5: Comparing the Three Approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*n4Civw0EHO1NEbkq5OO1nA.png" /></figure><h4>When Should You Use Each?</h4><ul><li><strong>Manual-Way-Simple: </strong>For <em>tiny scripts, prototypes, or CTF-style projects</em> where dependencies are few and change rarely.</li><li><strong>Manual-Way (Factory + DI): </strong>For <em>learning design patterns</em> or lightweight CLI apps where you want a taste of decoupled design without pulling in Spring.</li><li><strong>Spring-Way: </strong>For <em>production systems, microservices, or anything at scale</em>. Let the framework manage lifecycle, injection, configuration, and test contexts so you can focus on the logic.</li></ul><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qp9rfkBXUHMyoojpoq4joA.png" /><figcaption><strong>Factory Pattern → Dependency Injection → Spring Boot</strong></figcaption></figure><p>Each layer removes friction, reduces coupling, and adds flexibility. And now, when you see <strong><em>@Bean</em></strong> or <strong><em>@Autowired</em></strong>, you’ll know exactly what’s happening under the hood.</p><h3>Questions I had while implementing…</h3><p><strong>“My IDE says the <em>@Bean paymentProcessor(…)</em></strong> <strong>method is unused.” </strong>Spring calls it reflectively at startup. <strong>It <em>is</em> used by the container</strong>. Remove it only if you annotate the class with <strong><em>@Component</em></strong> and let component scanning create it.</p><p><strong>“What does <em>@ConditionalOnMissing</em> really do?” It prevents bean clashes.</strong> If some other configuration already provides a <strong><em>PaymentGateway</em></strong>, your default bean is <strong>skipped</strong> — perfect for profile-based overrides or auto-configs.</p><p><strong>“Why not just use <em>if/else</em></strong> <strong>everywhere?” </strong>Because change happens. Centralizing creation and delegating choice to configuration keeps your code closed for modification and open for extension, the whole point of DI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*_54SITcfznWIQfCxJOW9mg.gif" /></figure><h3>Final Thoughts</h3><p>The journey from <strong>manual object creation</strong> to <strong>framework-managed dependency injection</strong> mirrors the growth curve of every developer.</p><p>At first, you just want things to work. Then, you want them to scale. Finally, you want them to be clean, testable, and configurable — without reinventing the wheel.</p><p>That’s when the <strong>Factory Pattern</strong> evolves into <strong>Dependency Injection</strong>, and <strong>Dependency Injection</strong> evolves into <strong>Spring Boot</strong>.</p><p>You built the magic manually. Now you understand how Spring does it for you — elegantly, invisibly, and at scale.</p><h3>The code!</h3><p>Organized by learning stage:</p><ul><li><strong>manual-way-simple</strong> → naive, <strong><em>new</em></strong></li><li><strong>manual-way</strong> → factory + mini DI container</li><li><strong>spring-way</strong> → <strong><em>@Bean</em></strong> factories, enum/profiles, and conditional beans</li></ul><p>You can find the code for all of this in this <a href="https://github.com/MRegra/factory-pattern-medium-post">repo</a>. If you have any feedback or questions, please don&#39;t hesitate to let me know in the comments.</p><p>Thank you for reading, see you in the next one</p><p><strong><em>Cheers,</em></strong></p><p><strong><em>Marcelo</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0898bda4c7d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>