简体   繁体   中英

Grails initialization

In my Grails app, I need access to configuration exposed by a Java class similar to the below

public class Config {

  private Properties properties = new Properties(); 

  static load(String path) {
    File configFile = new File(path);
    FileReader fileReader = new FileReader(configFile);
    properties.load(fileReader);
  }

  String getProperty(String name) {
    properties.getProperty(name);
  }
}

I trigger the initialisation of this class in the first line of Bootstrap.groovy by calling Config.load("/conf.properties") . However, the initialization of various Spring beans needs properties that are exposed by Config , but by the time Bootstrap.groovy is executed, Spring initialization has already completed.

So I need to find a way to call Config.load() before construction of the Spring beans, is this possible? I guess there might be an event handler available in /script/_Events.groovy that I could invoke it from, but I'm not sure which handlers are available.

Unfortunately, changing the source code of Config.java isn't an option, and neither is eliminating my usage of this class.

You could try declaring a suitable bean in web-app/WEB-INF/applicationContext.xml , which is the definition of the root web application context as opposed to the GrailsApplication's internal context.

<bean id="initConfig" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetClass" value="com.example.Config" />
  <property name="targetMethod" value="load" />
  <property name="arguments">
    <list><value>/conf.properties</value></list>
  </property>
</bean>

and modify the grailsApplication bean to depend on that:

<bean id="grailsApplication" depends-on="initConfig" class="...">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM