Search code examples
javadependency-injectioncdiinject

Are getters and setters needed for CDI injected beans?


When a bean is injected using CDI:

@Inject Person person;

Is a setter and getter needed/recommended?

import javax.inject.Inject;
import javax.inject.Named;

@Named
@SessionScoped
public class myJSFBean{

  @Inject Person person;

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

I have found this documentation, but I don't understand what it means: http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html


Solution

  • According to Weld Documentation:

    Notice that it isn’t necessary to create a getter or setter method to inject one bean into another. CDI can access an injected field directly (even if it’s private!), which sometimes helps eliminate some wasteful code. The name of the field is arbitrary. It’s the field’s type that determines what is injected.