主要步骤如下:
1、建一个自己的监听器实现ServletContextListener接口;
2、实现contextInitialized方法,在此方法中加载配置文件信息;
3、在web.xml中配置监听器的信息。
实例代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class WebAppEventListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { final ServletContext context = sce.getServletContext(); String path = context.getRealPath("/"); MyApplication.initlize(path); } } public class MyApplication { private static String webPath = null; private static String xxxxxx; public static void initlize(String webPath) { MyApplication.webPath = webPath; //app.properties放在resource根目录下 InputStream is = MyApplication.class.getClassLoader().getResourceAsStream("app.properties"); if (is == null) { return; } Properties p = new Properties(); p.load(is); is.close(); xxxxxxx = p.getProperty("xxxx.xxx.xxxx"); }
我们知道spring mvc的核心控制器是一个servlet(DispatcherServlet),所以我们配置的servlet监听器要记得放在springmvc前面哦!
复制代码
1
2
3
4
5
6
7
8<listener> <listener-class>com.xxxx.xxx.xx.WebAppEventListener</listener-class> </listener> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> ... </servlet>
如果对您有用的话赞一下呗!谢谢啦!
最后
以上就是温婉身影最近收集整理的关于java开发——在servlet容器初始化时加载配置文件(.properties)的信息的全部内容,更多相关java开发——在servlet容器初始化时加载配置文件(.properties)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复