I'm having some problems using CDI with Tommahawk Myfaces when trying to create a JSF page to upload a file. Referring to this question it looks as though Tommahawk MyFaces isn't compatible with CDI but is this correct?
My Bean is like this:
@ManagedBean
@RequestScoped
public class Bean {
private UploadedFile uploadedFile;
public void submit() throws IOException {
String fileName = FilenameUtils.getName(uploadedFile.getName());
String contentType = uploadedFile.getContentType();
byte[] bytes = uploadedFile.getBytes();
// Now you can save bytes in DB (and also content type?)
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileName, contentType)));
}
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
}
But as soon as I replace @ManagedBean
and @RequestScoped
with @Named
or @Model
I get the following warning when deploying:
WELD-001529 An InjectionTarget implementation is created for a class org.apache.myfaces.webapp.filter.TomahawkFacesContextFactory which does not have any appropriate constructor.
And when I upload a file with the following JSF page, the value of UploadedFile
is null when I use @Named
or @Model
. but not with @ManagedBean' and
@RequestScope. This is the
.xhtml` file and I do use tommahawk Myfaces:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:t="http://myfaces.apache.org/tomahawk"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Tomahawk file upload demo</title>
</h:head>
<h:body>
<h:form enctype="multipart/form-data">
<t:inputFileUpload value="#{bean.uploadedFile}" />
<h:commandButton value="submit" action="#{bean.submit()}" />
<h:messages />
</h:form>
</h:body>
</html>
So I assume CDI does not like the tomahawk library as there is no default constructor?
Looking at 'Begginning Java EE 7' it specifies that CDI 1.1 treats any class as a CDI bean which statifies (amongst other things) :
It has a default constructor with no parameters with no parameters , or it declares a constructor annotated @Inject.
It looks as though TomahawkFacesContextFactory doesn't fulfil this requirement.
** EDIT ** The above seems to be confirmed in the CDI specification here. I've switched to PrimeFaces too and again this has similar problems with CDI however I not on their announcement here that:
PrimeFaces 5.0 will ship with a new component model supported by annotation, and CDI compatible (or Spring or Guice!).