Java Reference
In-Depth Information
}
}
Here, we use the
@Context
annotation on the
setServletContext()
method of our
Cus-
tomerResource
class. When an instance of
CustomerResource
gets instantiated, the
setServletContext()
method is called with access to a
javax.servlet.ServletContext
.
From this, we can obtain the value of
max-customers-size
that we defined in our
web.xml
and save it in the member variable
defaultPageSize
for later use.
Another way you might want to do this is to use your
javax.ws.rs.core.Application
class as a factory for your JAX-RS services. You could define or pull in configuration in-
formation through this class and use it to construct your JAX-RS service. Let's first rewrite
our
CustomerResource
class to illustrate this technique:
@Path
(
"/customers"
)
public
public class
class
CustomerResource
CustomerResource
{
protected
protected
int
int
defaultPageSize
=
5
;
public
public
void
void
setDefaultPageSize
(
int
int
size
) {
defaultPageSize
=
size
;
}
@GET
@Produces
(
"application/xml"
)
public
public
String
getCustomerList
() {
...
use defaultPageSize to create and
return
return
list of XML customers
...
}
}
We first remove all references to the
ServletContext
injection we did in our previous in-
carnation of the
CustomerResource
class. We replace it with a setter method,
setDe-
faultPageSize()
, which initializes the
defaultPageSize
member variable. This is a better
design for our
CustomerResource
class because we've abstracted away how it obtains con-
figuration information. This gives the class more flexibility as it evolves over time.
We then inject the
ServletContext
into our
Application
class and extract the needed in-
formation to initialize our services:
import
import
javax.ws.rs.core.Application
javax.ws.rs.core.Application
;
import
import
javax.naming.InitialContext
javax.naming.InitialContext
;
@ApplicationPath
(
"/"
)
public
public class
class
ShoppingApplication
ShoppingApplication
extends
extends
Application
{