Search code examples
jsfomnifaces

How to use org.omnifaces.cdi.settings.ApplicationSetting


I could not find any examples with explanation for this so I'm posting this question. I'm trying to pattern a java ee app from https://github.com/javaeekickoff/java-ee-kickoff-app. I added entries in the /META-INF/conf/application-settings.xml and inject it like so:

@Inject @ApplicationSetting
private String keyName;

but keyName comes up null. Also, under /conf there are /dev, /live, and /local-dev. Which application-settings.xml should I edit and how to specify which environment to use?


Solution

  • Using @ApplicationSetting is pretty straightforward. You use it like so:

    @Inject @ApplicationSetting
    private String keyName;
    

    keyName was returning null because I used keyName inside the constructor. It's not yet initialized so it won't work.

    @WebServlet("/example")
    public class Example extends HttpServlet {
        @Inject @ApplicationSetting
        private String keyName;
    
        public Example() {
            something = keyName // keyName is null
        }
        ...
    }
    

    To make the above code work, I needed a different lifecycle method than the constructor. Also, make sure your class is a CDI bean to be able to use @Inject @ApplicationSetting. So the fix is:

    @WebServlet("/example")
    public class Example extends HttpServlet {
        @Inject @ApplicationSetting
        private String keyName;
    
        @Override
        public void init() throws ServletException {
            something = keyName // keyName is NOT null anymore :)
        }
        ...
    }