【问题标题】:spring web application initialization from database on startup启动时从数据库初始化 web 应用程序
【发布时间】:2011-08-16 17:48:16
【问题描述】:

Spring 3.1 + Tomcat

我有一点设计问题:

在数据库中指定了一组类别。这些类别可以被认为是全局的,因为它们可以在整个 webapp 中使用。我想做的是在服务器启动时阅读这些类别并在 Java 中填充某种类型的集合。只需在启动时从数据库中读取一次,将其视为一种初始化。

我能想到的两个选项:

1) 我应该使用非延迟初始化的 bean 吗?

2) 修改web.xml?

我不太确定首选方法是什么,如果您能提供任何有关如何执行您推荐的方法的说明,我们将不胜感激。谢谢!

【问题讨论】:

    标签: spring jakarta-ee spring-mvc


    【解决方案1】:

    您提供的选项是最常用的:

    1. 使用带有 @PostConstruct 注释的方法的单例非惰性 bean(但请注意 @Transactional might not work)。您可以拥有多个具有此类初始化例程的 bean。

    2. 扩展org.springframework.web.context.ContextLoaderListener 并在web.xml 中使用它。我发现这个解决方案不太优雅,而且还推广了糟糕的编程风格(通过调用super 来增强基类)

    【讨论】:

    • 我选择了方法 1,但是我没有使用 PostContrust,而是在 bean 定义中使用了 init-method 属性,这似乎是我所需要的。
    • 是的,这完全一样。事实上init-method 是侵入性最小的(你也可以实现InitializingBean),因为它完全不依赖你的bean。
    【解决方案2】:

    我使用了实现ServletContextAwareInitializingBeanController。控制器在应用程序启动时运行,我在 afterPropertiesSet 方法中运行我的参数加载代码,以便正确注入 ServletContext。然后这些属性在 ServletContext 的整个应用程序中都可用。代码:

    @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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 2011-01-23
      • 2011-11-17
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多