---
title: " struts 中的 PlugIn "
author: "dmwdmc"
date: "2011-11-02T12:43:46Z"
tags: []
categories: ["Web前端"]
slug: "struts-plugin"
draft: false
lastmod: "2011-11-02T12:43:46Z"
id: 1230118
url: "https://dmwdmc.iteye.com/blog/1230118"
---

# 问题：有时候你需要在应用程序启动时装载一些数据到程序上下文中或执行某些操作。    
# 解决方法： 创建一个实现了 org.apache.struts.action.PlugIn接口的类文件并在struts-config.xml中设置plug-in元素。以下代码片段显示了一个plug-in生命声明和一个自定义的set-property子元素： 

<plug-in className="com.oreilly.strutsckbk.CustomPlugin" >
  <set-property property="customData"
                   value="Hello from the plugin"/>
</plug-in>  

# 细节讨论：Struts提供一个 PlugIn接口能使你在启动应用程序时为你提供自定义的操作。其源代码如下： 

package org.apache.struts.action;   
  
import javax.servlet.ServletException;    
import org.apache.struts.config.ModuleConfig;  
  
public interface PlugIn {   
  
    void destroy();   
  
    void init(ActionServlet servlet, ModuleConfig config)    
        throws ServletException;   
} 

要实现一个plug-in，你只需要实现这个接口并在struts-config.xml文件的中声明plug-in元素。子类必须实现方法 destroy()和init()。init()在ActionServlet启动时实例化plug-in过程中执行，当ActionServlet结束时执行destroy(),一般情况下是应用程序关闭。通过在plug-in元素中设置set-property元素，可以向PlugIn类传递参数。 所有set-property元素都在init()方法执行之前被执行，这样就可以在init()方法中使用这些由set-property设置的参数了。 Struts将ActionServlet的引用和ModuleConfig参数传递给init()方法。ActionServlet使的 init()方法中可以将数据保存到ServletContext中。ActionServlet还可以使你能够访问更多的J2EE组件如java sources、message队列等。ModuleConfig可以让你访问当前的模块配置信息。