gpt4 book ai didi

java - 从方法返回的值可以分配给常量吗?

转载 作者:行者123 更新时间:2023-12-04 11:28:39 25 4
gpt4 key购买 nike

我想在 SpringBoot 中格式化一些文件,每个文件都有一个请求。对于每个请求,我都必须调用 getOutputFolder(dirName) 方法来获取输出路径,以便将文件保存在预期路径中,但我的解决方案的开销成本很高。我想定义一个常量,然后当我必须调用该函数时,我改为调用它。但我觉得这似乎是错误的,或者至少是一种偷偷摸摸的方式。有没有更好的方法来解决这个问题?

private static final String OUTPUT_FOLDER_PATH = getOutputFolderPath();

private String getOutputFolder(String dirName) {
String pathStr = getOutputFolderPath() + dirName + File.separator + "submit" + File.separator;
Path outputDirPath = Paths.get(pathStr);

Path path = null;
boolean dirExists = Files.exists(outputDirPath);
if (!dirExists) {
try {
path = Files.createDirectories(outputDirPath);
} catch (IOException io) {
logger.error("Error occur when create the folder at: {}", pathStr);
}
}
return dirExists ? pathStr : Objects.requireNonNull(path).toString();
}

最佳答案

您可能想查看 jcache .

为此,您需要将其安装到您的 Spring Boot 项目中

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'javax.cache:cache-api:1.1.0'

// or the maven equivalent if you are using maven

然后创建一个 org.springframework.cache.CacheManager bean 来配置缓存。

@Bean
public CacheManager cacheManager() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();

// The class arguments is <String, String> because the method to cache accepts a String and returns a String
// just explore this object for the config you need.
MutableConfiguration<String, String> configuration = new MutableConfiguration<>();

String cacheName = "OUTPUT_FOLDER_CACHE";
cacheManager.createCache(cacheName, configuration);
return cacheManager;
}

设置完成后,您现在可以注释要缓存的方法。

@Cacheable(
cacheNames = { "OUTPUT_FOLDER_CACHE" }, // The same string in config
unless = "#result == null" // Dont' cache null result; or do, if you need it.
)
String getOutputFolder(String dirName) {
// method contents...
}

正确配置时:如果存在,方法将返回缓存值,或者运行实际方法,缓存结果并在缓存值不存在时返回结果。

关于java - 从方法返回的值可以分配给常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60144448/

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