×
☰ See All Chapters

JSF Dependency Injection - ManagedProperty

JSF @ManagedProperty annotation is used to inject the dependencies instead of object having to acquire those dependencies on its own.

With Dependency Injection

Without Dependency Injection

import javax.faces.bean.ManagedBean;

@ManagedBean (name="user")

public class UserDto {

        String name;

        //Setters and Getters

}

--------------

import javax.faces.bean.ManagedBean;

import javax.faces.bean.ManagedProperty;

 

@ManagedBean

public class HelloBean {

       // value attribute is mandatory        

       @ManagedProperty(value="#{user}")

        private UserDto userDto = null;

 

        public UserDto getUserDto() {

                return userDto;

        }

        public void setUserDto (UserDto userDto) {

                this.userDto = userDto;

        }

}

import javax.faces.bean.ManagedBean;

@ManagedBean

public class UserDto {

        String name;

        //Setters and Getters

}

--------------

import javax.faces.bean.ManagedBean;

@ManagedBean

public class HelloBean {

        private UserDto userDto = new UserDto();

}

 

Property from injected object can be accessed through simple access approach in facelets.

<h:outputText value="Enter your name" />

<h:inputText id="nme" value="#user.name}" />

Property from injected object can be accessed through deep access approach in facelets.

<h:outputText value="Enter your name" />

<h:inputText id="nme" value="#{helloBean.userDto.name}" />

Objects of ManagedBean are injected automatically.

You have to Inject Objects of ManagedBean using new keyword.

Dependency Injection injects object dependencies, only whichever is necessary, so Dependency injection makes it possible to eliminate, or at least reduce, a components unnecessary dependency. So component is less vulnerable to change in its dependencies.

Components are more vulnerable to change in its dependencies. If a dependency changes, the component might have to adapt to these changes. For instance, if a method signature of a dependency is changed, the component will have to change that method call. 

Ideally Java classes will be as independent as possible from other Java classes. This increases the code reusability. Possibility of reusing these classes and to be able to test them independently from other classes.

Code reusability will be less.

Will be able to test the classes independently from other classes.

Not able to test the classes independently from other classes.

 


All Chapters
Author