Spring Initialization of web applications from the database at startup

Spring 3.1 + Tomcat

I have some design questions here:

There is a group of categories specified in the database. These categories can be considered global in the sense that they can be used throughout the webapp. What I would like to do is read these categories at server startup and populate some type of collection in Java. The only thing you need to read from the database once at startup is to consider this type of initialization.

Two options that I can think of:

1) Should I use a NAN-lazily initialized bean?

or

2) Change web.xml?

I'm not quite sure which method is preferred, and any instructions on how to implement your recommendations would be much appreciated. Thanks!

+3
source share
2 answers

The most commonly used parameters that you provide are:

  • Use singleton non-lazy bean using the method annotated with @PostConstruct (but keep in mind that @Transactional may not work ). You can have multiple beans with this initialization.

  • Extend org.springframework.web.context.ContextLoaderListener and use it in web.xml . I find this solution less elegant, while also promoting a bad programming style (expanding with super to improve the base class)

+4
source

I used a Controller that implements both ServletContextAware and InitializingBean . The controller starts when the application starts, and I run the parameter loading code in the afterPropertiesSet method afterPropertiesSet that the ServletContext is correctly entered. Properties are then available throughout the application from ServletContext. The code:

 @Controller public class ParameterizationController implements ServletContextAware , InitializingBean { protected final Log logger = LogFactory.getLog(getClass()); public static final String PARAMETERS_SC_ATTRIBUTE = "allProps"; private ServletContext sc; public ParameterizationController() { logger.info("inside ParameterizationController..."); } @Autowired private SomeService someService; @RequestMapping("/loadparams.do") public String formHandler( Model model) { String forwardValue = "/loadparams"; // an admin can also call this page to reload props at runtime this.sc.setAttribute(PARAMETERS_SC_ATTRIBUTE, loadProperties()); return forwardValue; } private HashMap<Integer, HashMap<String, String>> loadProperties() { return someService.loadProperties(); } // makes sure the SC is injected for use public void setServletContext(ServletContext sc) { this.sc = sc; } // only runs after all injections have been completed public void afterPropertiesSet() throws Exception { this.sc.setAttribute(PARAMETERS_SC_ATTRIBUTE, loadProperties()); } 
+3
source

All Articles