Search code examples
jsfmanaged-beanpostconstructfacescontext

FacesContext instance is null in ApplicationScoped Managedbean


I created a ApplicationScoped bean that have a PostConstruct method named start. Whenever i want to get instance of FacesContext in the start method and it returns null:

@ManagedBean
@ApplicationScoped
public class RemoveOldFilesScheduler implements Serializable {

    @PostConstruct
    private void start() {
        final FacesContext facesContext = FacesContext.getCurrentInstance();
        if(facesContext != null) {
            String realDownloadDirName = facesContext.getExternalContext().getRealPath("/") + DOWNLOAD_DIRECTORY;
        File downloadDir = new File(realDownloadDirName);
        if (downloadDir.exists()) {
            removeOldFiles(downloadDir.listFiles());
        }
}
}

How can i access to facesContext in this situation?

I want to get real path of my download directory in the start method and i don't know how to get path of my directory without using FaceContext.

Is there another way to do it?


Solution

  • I implementing my class as Listener and it worked and i can access to ServletContext in contextInitialized method :

        public class RemoveOldFilesListener implements ServletContextListener {
    
        public ServletContext servletContext;
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            servletContext = sce.getServletContext();
            String realDownloadDirName = servletContext.getRealPath("/") + DOWNLOAD_DIRECTORY;
            File downloadDir = new File(realDownloadDirName);
            if (downloadDir.exists()) {
                removeOldFiles(downloadDir.listFiles());
            }
    }