在web应用中如果自已的程序里面需要用到外部资源文件(配置文件),一般会把配置文件放在classes下面或web-inf下面。如果加载这结文件的话通常有两种办法。一是写绝对路径,这是最不推荐的方法。二是引入servletcontext,从相对路径中获得绝对路径。 写相对路径的时候使用servletcontext是免不了的,我的应用服务器是tomcat,使用相对路径找文件都是在tomcat的bin文件夹下面找,所以我只能用servletcontext来找。后来,为了使程序能脱离servlet容器运行,就引入了spring的资源管理机制。
spring为资源管理提供了一个resource接口,并提供了几个resource的实现。它们都需要一个string表示的资源的实际位置。依据这个string,spring将会自动为你选择正确的resource实现。
下面一段代码,我为了得到一个资源的位置,定义了个属性,一个是file代表文件的路径(相对或绝对),一个是resouce接口的属性。在spring的任何context中都可以通过设置resource的属性来得到资源的位置。
| private string file; private resource resource; public void setresource(resource resource) { this.resource = resource; try { this.file = resource.getfile().getabsolutepath(); } catch (ioexception e) { e.printstacktrace(); throw new runtimeexception(e.getmessage()); } } public void setfile(string file) { this.file = file; } |
| <bean id="mybean" class=.net.jf.mybean"> <property name="resource"> <value>/web-inf/config.xml</value> </property> </bean> |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器