【发布时间】:2019-01-15 19:01:17
【问题描述】:
我在下面用 args 编写了 Spring Boot 应用程序。
java jar ... --credential="path\credentials.properties"
像这样从控制台运行。我从控制台获取属性文件路径,当我需要一个属性时,首先我加载属性文件,然后用我的密钥获取我的属性。我怎样才能避免它?我只想加载一次属性文件,以后总是想使用第一个加载的文件。我不想一次又一次地加载。像这样,我不想调用它的属性。
@SpringBootApplication
@Slf4j
class ProRunner implements CommandLineRunner {
@Autowired
AnalyzeManager analyzeManager;
@Autowired
AuthService authService;
@Autowired
WriterService writerService;
static void main(String[] args) {
SpringApplication.run(ProRunner.class, args);
}
@Override
void run(String... args) throws Exception {
try {
String token = authService.postEntity("url", args).token;
Map dataSet = analyzeManager.bulkCreate(args);
writerService.write(args, dataSet)
} catch (Exception e) {
e.printStackTrace();
}
}
}
在每个服务(authService、analyzeManager、writerService)中,我根据 args 加载属性。稍后继续我的流程。
为了加载属性,我创建了一个 Util 方法,并且每次都调用它。
public class Utils {
public static Properties getProperties(String...args) throws IOException {
File file = new File(args[0]);
Properties properties = new Properties();
InputStream in = new FileInputStream(file);
properties.load(in);
return properties;
}
}
属性文件包含以下内容:
- username
- password
- outputFileName
- startDate
- endDate
...
【问题讨论】:
-
为什么你不能使用spring`s propertyplace holder Sample
-
@Barath ,属性文件不是常量。它取自控制台作为参数。
-
一旦属性文件作为参数传递,属性是不可变的。您可以使用属性占位符,它将属性直接加载到 spring 的环境中。你可以让春天发挥它的魔力。
-
@Barath,请给我一些关于我的例子的实现。就像,我们的自定义属性上有用户名和 startDate。我们如何为这个例子集成它的弹簧属性?
-
Utils应该是一个 Spring 托管的 bean,其中属性在应用程序初始化期间加载一次。另外,考虑添加getUserName()、getPassword()等来隐藏/封装属性键而不暴露属性对象。根据您的描述,Utils应命名为CredentialsProvider。
标签: java spring spring-boot properties