gpt4 book ai didi

java - 加载 Web 应用程序属性

转载 作者:行者123 更新时间:2023-12-02 10:49:04 31 4
gpt4 key购买 nike

当我通过maven构建项目时,一切正常,但是当我通过Tomkat部署它时,出现NullPointerException。类,哪里可能有问题 - PropertiesManager。日志行:PropertiesManager.getApplicationProperties(PropertiesManager.java:31)

public class PropertiesManager {
private static final String PROPERTY_FILE_NAME =
"resources/application.properties";
private static PropertiesManager Instance;
private Properties properties;

private PropertiesManager() {
}

public static PropertiesManager getInstance() {
if (Instance == null) {
Instance = new PropertiesManager();
}
return Instance;
}

public Properties getApplicationProperties() {
if (properties == null) {
properties = new Properties();
try (InputStream stream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(PROPERTY_FILE_NAME)) {
properties.load(stream);
} catch (IOException e) {
throw new ApplicationException("Failed to load property file", e);
}
}
return properties;
}
}

和日志行:ApplicationLifecycleListener.contextInitialized(ApplicationLifecycleListener.java:14)ApplicationLifecycleListener 类:

public class ApplicationLifecycleListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
Properties applicationProperties = PropertiesManager.getInstance().getApplicationProperties();
DBManager.getInstance().initialize(applicationProperties);
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
DBManager.getInstance().stopDb();
}
}

问题可能是什么?

最佳答案

如果不向文件提供确切的行,您会看到 NullPointerException (您提供的文件都没有日志中显示的行),很难确定。但有一个提示是,尽管您将要使用 Maven 构建的资源文件放在 '<project>/src/main/resources' 中。文件夹,当构建并打包 war 文件时,它会将您的应用程序资源文件放在 'WEB-INF/classes' 中文件夹是应用程序默认类路径的一部分。因此,要使用Thread.currentThread().getContextClassLoader().getResourceAsStream(...)方法正确引用它们您不应该添加 'resources\...'文件名的前缀,因为此方法已经在默认应用程序类路径中查找文件。删除前缀并查看是否有效。请引用这个answer了解更多详情。

关于java - 加载 Web 应用程序属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319033/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com