JAX-RS and CDI / @Provider and beans.xml
superdev May 10, 2012 10:02 AMI made a simple project that make use of JAX-RS (RESTfull service)
I have a JAX-RS (RESTfull service) webservice project that deploys to JBoss 6.1. resteasy integrated with JSON is provided by JBoss 6.1 by default. I wanted to change the date format of default JSON resource.
I got some help from the Internet and added a class extends JacksonJsonProvider:
http://stackoverflow.com/questions/8498413/accessing-jackson-object-mapper-in-resteasy
@Provider
@Produces("application/json")
public class MyJacksonJsonProvider extends JacksonJsonProvider {
public static final String pattern = "YYYY-MM-dd'T'HH:mm:ss";
@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
ObjectMapper mapper = locateMapper(type, mediaType);
// Set customized date format
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
mapper.getSerializationConfig().setDateFormat(sdf);
super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}
}
This works well until I added an empty beans.xml under WebContent/WEB-INF for CDI injection.
MyJacksonJsonProvider won't call, I still get default JSON date format.
Even I added the following dependency under pom.xml did not help.
<dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-cdi</artifactId> <version>2.2.1.GA</version> </dependency>
Does anyone have any idea why "MyJacksonJsonProvider" will be ingnored if I have an empty beans.xml under "WebContent/WEB-INF" folder? Thanks a lot in advance!
FYI, this is the sample model class:
@XmlRootElement(name = "movie")
public class Movie {
String name;
String director;
int year;
Date date;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
@XmlAttribute
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@XmlElement
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
And this is the class that produces JSON resource:
@Path("/json/movie")
public class JSONService {
@GET
@Path("/get")
@Produces("application/json")
public Movie getMovieInJSON() {
Movie movie = new Movie();
movie.setName("Little flower");
movie.setDirector("Zhang Zheng");
movie.setYear(1979);
movie.setDate(new Date());
return movie;
}
}