Wiki
Clone wikiOracle JSF Expert 1Z0-896 / Named Beans
Advantages over JSF Managed beans
- Allows for JEE wide dependency injection
- POJOS can be injected
- Can inject
@Named
beans into JSF beans @ManagedProperty
injection ONLY works inside a JSF@ManagedBean
- Having getter and setter methods ISN'T required for
@Named
beans that are injected using@Inject
Using @Inject - javax.inject.Inject
Constructor injection
public class MyBean { private MyDependency dependency; @Inject public MyBean(MyDependency dependency) { this.dependency = dependency; } }
Setter injection
public class MyBean { private MyDependency dependency; @Inject public void setDependency(MyDependency dependency) { this.dependency = dependency; } }
Field injection
public class MyBean { @Inject private MyDependency dependency; }
Using @PostConstruct - javax.annotation.PostConstruct
CDI calls the method after all injection has occurred and after all initializers have been called.
@Named public class CustomerBean { @Inject private CustomerService customerService; private List<Customer> customers; @PostConstruct public void init() { customers = customerService.findAll(); } }
Using @PreDestroy - javax.annotation.PreDestroy
Used for example to release resources before destroying a bean
/** * Admittedly a contrived example */ @Named public class MyBean { private InputStream inputStream; @PostConstruct public void init() { // Open input stream for reading from } @PreDestroy public void destroy() { // Close input stream before destroying bean } }
Updated