-
Notifications
You must be signed in to change notification settings - Fork 29
using Easy Props in a web environment
Using Easy Props to inject properties in web components is straight forward. Like any other object, all you need to do is to annotate your instance variable with Easy Props annotations and provide a setter for this variable.
Usually, web frameworks provide initialization methods in components lifecycle, you can call Easy Props code inside these methods.
This section will show how to use Easy Props to inject properties in several web frameworks components.
The servlet API provides an initialization method init
that is called when a servlet is first initialized by the container. This is a good place to call Easy Props code to inject properties in the servlet instance variables.
public class MyServlet extends HttpServlet {
@SystemProperty(value = "user.home", defaultValue = "/home/me")
private String userHome;
@Override
public void init() throws ServletException {
aNewPropertiesInjector().injectProperties(this);
}
public void setUserHome(String userHome) {
this.userHome = userHome;
}
}
In this example, Easy Props will inject the System property user.home
in the userHome
field when the servlet MyServlet
is first initialized by the container.
Struts 2 provides an initialization hook for actions through the Preparable interface.
The following example shows how to inject the System property user.home
in the userHome
field of the MyAction
action when it is initialized by Struts.
public class MyAction extends ActionSupport implements Preparable {
@SystemProperty(value = "user.home", defaultValue = "/home/me")
private String userHome;
public void prepare() throws Exception {
aNewPropertiesInjector().injectProperties(this);
}
public void setUserHome(String userHome) {
this.userHome = userHome;
}
}
Note that the prepare
interceptor should be enabled, as mentioned in Struts documentation here.
Tapestry 5 provides an initialization hook for pages through the Activate event.
The following example shows how to inject the System property user.home
in the userHome
field of the MyPage
page when it is initialized by Tapestry.
public class MyPage {
@SystemProperty(value = "user.home", defaultValue = "/home/me")
private String userHome;
@OnEvent(EventConstants.ACTIVATE)
public void init(){
aNewPropertiesInjector().injectProperties(this);
}
public void setUserHome(String userHome) {
this.userHome = userHome;
}
}
NB: Tapestry 5 provides its own IoC container so it's probably possible to inject (system) properties or environment variables in tapestry pages. That said, if this is not possible, the sample above shows how to do it with Easy Props.
Easy Properties is created by Mahmoud Ben Hassine and the awesome contributors
-
Introduction
-
Documentation