Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use @Value annotation to get system property in ServletContextListener

I have a ServletContextListener in my web application. The following works...

public class AppServletContextListener 
               implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {

      public void contextInitialized(ServletContextEvent arg0) {

            String repManInitScript = System.getProperty("REP_MAN_INIT_SCRIPT");
            System.err.println(repManInitScript ); 
       }
}

But usign the @Value annotation doesn't....

public class AppServletContextListener 
               implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {

@Value("${REP_MAN_INIT_SCRIPT}")
private String repManInitScript; 

      public void contextInitialized(ServletContextEvent arg0) {

            repManInitScript = System.getProperty("REP_MAN_INIT_SCRIPT");
            System.err.println(repManInitScript ); 
      }
}

Is there a way to grab the system property using the @Value annotation?

Thanks

like image 417
Richie Avatar asked Oct 19 '25 03:10

Richie


1 Answers

Yes you can but you have to grab it from the system properties like this:

@Value("#{systemProperties['REP_MAN_INIT_SCRIPT']}")
private String repManInitScript;

I assume you already have this property in your system properties.

And of course @Value annotation only works in spring beans. If you try to use it directly in ServletContextListener it won't work.

This ${REP_MAN_INIT_SCRIPT} isn't working because spring looks for the property in your configured properties if you have any of course.

So if you want this to work on initialization you can implement InitializingBean in your spring bean and override afterPropertiesSet method. Then the value will be available.

like image 146
Paulius Matulionis Avatar answered Oct 21 '25 01:10

Paulius Matulionis