I recently saw a post that explained in JAVA EE, instead of using a .properites
file, a better way to specify Configuration Properties is in a web.xml
file and then injecting them inside the Class where the properties are needed.
This is my Web.xml
<env-entry>
<env-entry-name>pacakageName.ClassName/number</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>123</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>country</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Spain</env-entry-value>
</env-entry>
And in my Java class, when I use the JNDI way I am able to get the value
InitialContext initialContext = new javax.naming.InitialContext();
String countryName = (String) initialContext.lookup("java:comp/env/country");
This works, but when I try to use the new way of using @Resources
and injecting the value, the value is not read from the web.xml
@Path("loginService")
public class LoginService{
@Resource() int number;
//constructor and other methods
}
I am using Tomcat 7...Could anyone help me out what I am doing wrong.
I referred this doc: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/env_entry/env_entry.html
Your class is not the kind that supports the @Resource
annotation. It needs to be a Java EE component, like an EJB for example.
This is because the container is the one that injects the resources, and it only considers components as valid injection targets. Also for this reason the resource must be defined before the container starts, so you can't inject resources that you put into JNDI during runtime.