Kap*_*psh 8 java servlets properties
我有一堆可以根据环境改变的属性(配置).但是,一旦部署了Web应用程序,这些值就不会更改.因此,我认为有一个application.properties文件,我想在正常的程序流程中多次阅读.
我知道我可以在服务器启动时加载这些.但是,对于从后端的简单java类访问这些内容,最好的做法是什么?这些业务类与servlet等无关,并且不依赖于webapp.
所以今天我通过ServletContext加载属性.那又怎样?我应该在哪里保留它们以便其他对象可以轻松访问而无需再次执行fileInputStream.load?
谢谢.
Bal*_*usC 13
这是一个基本的启动示例:
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();
@Override
public void contextInitialized(ServletContextEvent event) {
try {
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
} catch (IOException e) {
throw new SomeRuntimeException("Loading config failed", e);
}
event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
public static Config getInstance(ServletContext context) {
return (Config) context.getAttribute(ATTRIBUTE_NAME);
}
public String getProperty(String key) {
return config.getProperty(key);
}
}
Run Code Online (Sandbox Code Playgroud)
你注册如下web.xml:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
您可以在servlet中访问,如下所示:
Config config = Config.getInstance(getServletContext());
String property = config.getProperty("somekey");
Run Code Online (Sandbox Code Playgroud)
经过深思熟虑后,这些属性因此100%特定于业务层,而不是Web应用程序本身?然后a ServletContextListener确实笨拙且太紧.只需为业务层提供自己的Config类,该类从类路径加载属性并将其缓存在某个static变量中(Map<String, Properties>可能是?).
| 归档时间: |
|
| 查看次数: |
11308 次 |
| 最近记录: |