Search code examples
javaspringsetterrequired

Why is @Required set for setters and not fields?


If I have the following class:

package com.example;

import org.springframework.beans.factory.annotation.Required;

public class Customer 
{
    private Person person;

    public Person getPerson() {
        return person;
    }
    @Required
    public void setPerson(Person person) {
        this.person = person;
    }
}

Why in Spring is the @Required tag tied to the setter, and not the field, like this?

package com.example;

import org.springframework.beans.factory.annotation.Required;

public class Customer 
{
    @Required
    private Person person;

    public Person getPerson() {
        return person;
    }
    public void setPerson(Person person) {
        this.person = person;
    }
}

The dependency is that the property is set, but doesn't need to be tied down to one specific setter that populates that property or field, unless I'm missing something.


Solution

  • Traditionally a bean had properties defined as a getter and/or setter. The private field can be left out (sometimes name "virtual" field). In the new Java EE standard beans are more loose, and might also have a property defined as public field.

    Nevertheless Spring pre-dates the latest standard, and having the annotation on a method i.o. a field has the advantage that access can be intercepted via AOP (simple byte code manipulation).