Java 在整个应用程序中只向应用程序加载一次属性

Java 在整个应用程序中只向应用程序加载一次属性,java,initialization,Java,Initialization,我使用以下代码从Java应用程序中的文件加载属性 private Resource resource = new ClassPathResource("/config.properties"); private Properties properties = PropertiesLoaderUtils.loadProperties(resource); private List<String> connectionParameters = Arrays.asL

我使用以下代码从Java应用程序中的文件加载属性

    private Resource resource = new ClassPathResource("/config.properties");
    private Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    private List<String> connectionParameters = Arrays.asList(properties.getProperty("connection").split(","));
private Resource=new ClassPathResource(“/config.properties”);
私有属性=PropertiesLoaderUtils.loadProperties(资源);
私有列表connectionParameters=Arrays.asList(properties.getProperty(“连接”).split(“,”);
但我不希望在将属性加载到connectionParameters中后再次调用此代码。我不希望再次调用加载逻辑,我希望只要应用程序处于活动状态,列表就处于活动状态并可用


有办法做到这一点吗

您可以使用a并只加载一次。

您可以使用a并只加载一次。

您可以简单地将这些字段转换为静态字段,以确保它们在类初始化时只初始化一次,如下所示:

private static final Resource resource = new ClassPathResource("/config.properties");
private static final Properties properties = PropertiesLoaderUtils.loadProperties(
    resource
);
private static final List<String> connectionParameters = Arrays.asList(
    properties.getProperty("connection").split(",")
);
private static final Resource=new ClassPathResource(“/config.properties”);
私有静态最终属性=PropertiesLoaderUtils.loadProperties(
资源
);
私有静态最终列表connectionParameters=Arrays.asList(
properties.getProperty(“连接”).split(“,”)
);

实际上,当类由
类加载器初始化时,静态字段和静态块只初始化/执行一次
类加载器
您可以简单地将这些字段转换为静态字段,以确保它们在类初始化时只初始化一次下一步:

private static final Resource resource = new ClassPathResource("/config.properties");
private static final Properties properties = PropertiesLoaderUtils.loadProperties(
    resource
);
private static final List<String> connectionParameters = Arrays.asList(
    properties.getProperty("connection").split(",")
);
private static final Resource=new ClassPathResource(“/config.properties”);
私有静态最终属性=PropertiesLoaderUtils.loadProperties(
资源
);
私有静态最终列表connectionParameters=Arrays.asList(
properties.getProperty(“连接”).split(“,”)
);

实际上,static字段和static块仅在类由
ClassLoader

初始化时初始化/执行一次,但每次创建类实例时,那段代码不会被再次调用吗?不仅当类加载器第一次加载类时,而且每次创建类实例时,那段代码不会被再次调用吗?不仅当类加载器第一次加载类时,那段代码不会被再次调用吗?很好,谢谢。即使是另一个答案也是有意义的,而且使用起来更方便。:-)向上投票。听起来不错,谢谢。即使是另一个答案也是有意义的,而且使用起来更方便。:-)向上投票。