Skip to main content

๐Ÿ’ฅ "Wait... Why Is It NULL?!?" — When @Value("${...}") Ignores Your Static Field ๐Ÿ˜ต‍๐Ÿ’ซ

๐Ÿ”  A surprising Spring Boot moment I didn't expect — and the rabbit hole it took me down...

๐ŸŽฌ It All Started With a Simple Idea...

You know how it goes…

You define a config value like this in application.properties:

payment.currency=INR

And then you boldly write this innocent-looking code:

@Component
public class PaymentUtil {

    @Value("${payment.currency}")
    private static String currency; // ✅ Logical! Right?

    public static void printCurrency() {
        System.out.println("Currency: " + currency);
    }
}

You run the app. And BAM ๐Ÿ’ฅ

Currency: null

๐Ÿ˜ต "Eh? I clearly defined the property. Is it not reading the file? Do I need a restart? Do I need to yell at my laptop?"

๐Ÿคฏ The Shocking Discovery

Spring doesn’t inject values into static fields.

Yes, my friend. Even if you beg it with @Value.

And trust me — it’s not a bug. It’s a feature. ๐Ÿ™ƒ

๐Ÿง  What Is This Dependency Injection (DI) Sorcery Anyway?

Let’s take a detour (the good kind — not the Bangalore traffic kind).

Spring uses Dependency Injection (DI) to manage your object graph using:

  • ๐Ÿ“Œ @Component / @Service / @Repository
  • ๐Ÿ“Œ @Autowired / @Value / Constructor injection
  • ๐Ÿ“Œ Reflection magic ๐ŸŽฉ✨

๐Ÿšง Why Static Fields Break the Magic

Spring manages beans as instances — objects in the ApplicationContext.

But static fields belong to the class itself, not an object.

// Instance-level: Works ✔️
@Component
public class ConfigReader {
    @Value("${app.name}")
    private String name;
}

// Static field: No bean owns it ❌
@Value("${app.name}")
private static String name;

So Spring scans the class and goes:

“Aha, no instance variable to inject into? Cool, I’ll move on.” ๐Ÿ˜Ž

That’s why:

  • ❌ You get null
  • ❌ Or default values
  • ❌ Or you stare at the screen questioning your life choices ๐Ÿซ 

๐Ÿ› ️ The Correct Fix That Surprised Me

✅ Option 1: Use @PostConstruct to Bridge Static + Instance

@Component
public class PaymentUtil {

    @Value("${payment.currency}")
    private String currency;

    private static String staticCurrency;

    @PostConstruct
    public void init() {
        staticCurrency = currency;
    }

    public static String getCurrency() {
        return staticCurrency;
    }
}

๐ŸŽ‰ Now currency is injected properly by Spring.

✅ Option 2: Use @ConfigurationProperties — The Cleaner Way

@Component
@ConfigurationProperties(prefix = "payment")
public class PaymentConfig {
    private String currency;

    public String getCurrency() { return currency; }
    public void setCurrency(String currency) { this.currency = currency; }
}
@Component
public class PaymentUtil {
    private final PaymentConfig config;

    public PaymentUtil(PaymentConfig config) {
        this.config = config;
    }

    public void printCurrency() {
        System.out.println("Currency: " + config.getCurrency());
    }
}

๐Ÿงผ Much cleaner, and easier to unit test!

๐Ÿง  But Wait… Why Can’t Spring Just Inject Into Static?

Let’s dig deeper.

  1. ๐Ÿ“ฆ Create object of the bean (e.g., PaymentUtil)
  2. ๐Ÿ” Reflectively access fields
  3. ๐Ÿ’‰ Inject values from application context
  4. ๐Ÿš€ Initialize the bean

But static fields don’t belong to any bean instance. So Step 2 breaks:

๐Ÿงต “Oops! There’s no object for me to inject into.”

It’s like trying to insert a USB drive into a photo of a laptop. ๐Ÿ™ƒ

๐Ÿ˜‚ Dumb Interview Question, Smart Answer

Q: "Can Spring inject values into static fields?"

A: "Only if Spring becomes a Jedi and rewrites the Java language spec."

๐Ÿงช Curious? Try This Yourself!

# application.properties
payment.currency=USD
@Component
public class TestUtil {
    @Value("${payment.currency}")
    private static String currency;

    public static void main(String[] args) {
        System.out.println("Currency = " + currency);
    }
}
Currency = null  // ๐Ÿ˜

๐Ÿงผ So What Did I Learn?

  • ๐Ÿ˜ฒ I Did This: @Value on a static field
  • ๐Ÿค” Expected: "INR"
  • ❌ Got: null
  • ✅ Fixed By: @PostConstruct or @ConfigurationProperties
  • ๐Ÿ’ก Lesson: Spring doesn’t inject into static — by design

๐ŸŒˆ Wrapping Up: From "What The Null?!" to "Aha!"

This was a “Why is it null?” moment that led to one of my best Spring learnings:

Spring is smart, but it only manages beans it creates.

Static fields live in their own world — away from the Spring container.

Always remember: With great power comes great bean lifecycle responsibility. ๐Ÿ•ธ️

๐ŸŽค Over to You!

Ever had a “Null surprise” like this in your config or bean wiring?

๐Ÿ‘‰ Share your moment in the comments — let’s laugh and learn together! ๐Ÿ˜„

Comments

Popular posts from this blog

๐Ÿ” Is final Really Final in Java? The Truth May Surprise You ๐Ÿ˜ฒ

๐Ÿ’ฌ “When I was exploring what to do and what not to do in Java, one small keyword caught my eye — final . I thought it meant: locked, sealed, frozen — like my fridge when I forget to defrost it.”   But guess what? Java has its own meaning of final… and it’s not always what you expect! ๐Ÿ˜… Let’s break it down together — with code, questions, confusion, jokes, and everything in between. ๐ŸŽฏ The Confusing Case: You Said It's Final... Then It Changed?! ๐Ÿซ  final List<String> names = new ArrayList <>(); names.add( "Anand" ); names.add( "Rahul" ); System.out.println(names); // [Anand, Rahul] ๐Ÿคฏ Hold on... that’s final , right?! So how on earth is it still changing ? Time to dive deeper... ๐Ÿง  Why Is It Designed Like This? Here’s the key secret: In Java, final applies to the reference , not the object it points to . Let’s decode this like a spy mission ๐Ÿ•ต️‍♂️: Imagine This: final List<String> names = new ArrayList <>(); Be...

๐ŸŒŸ My Journey – From Zero to Senior Java Tech Lead ๐ŸŒŸ

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. ๐Ÿ’ฏ Sounds crazy? Let me take you back. ๐Ÿ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . ๐Ÿงช Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...

๐ŸŽข Java Loops: Fun, Fear, and ForEach() Fails

๐ŸŒ€ Oops, I Looped It Again! — The Ultimate Java Loop Guide You Won't Forget “I remember this question from one of my early interviews — I was just 2 years into Java and the interviewer asked, ‘Which loop do you prefer and why?’” At first, I thought, “Duh! for-each is cleaner.” But then he grilled me with cases where it fails. ๐Ÿ˜ต That led me to explore all loop types, their powers, and their pitfalls. Let’s deep-dive into every major Java loop with examples &  real-world guidance so you'll never forget again. ๐Ÿ” Loop Type #1: Classic For Loop — “The Old Reliable” ✅ When to Use: You need an index You want to iterate in reverse You want full control over loop mechanics ✅ Good Example: List<String> names = List.of("A", "B", "C"); for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } ๐Ÿ”ฅ Reverse + Removal Example: List<String> item...