gpt4 book ai didi

java - 使用spring boot loader WarLauncher时如何加载war文件之外的属性文件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:15 24 4
gpt4 key购买 nike

我通过指定 WarLauncher(spring boot loader 的一部分)作为我的启动类创建了一个可执行的 war 文件。当所有配置文件(属性、spring 上下文等)都是我的资源文件夹的一部分时,它工作正常。我希望我的 war 的消费者需要控制属性文件。因此需要在 war 文件之外加载它。我期待配置文件夹中的属性文件(与 war 文件并排部署)。我试图通过使用 Maven 插件向 list 中添加适当的类路径条目,但没有成功。

以下是我的 maven POM 文件的相关部分的样子:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>org.springframework.boot.loader.WarLauncher</mainClass>
</manifest>
<manifestEntries>
<Start-Class><<myclass_dont_worry_about_this>></Start-Class>
<Class-Path>config/</Class-Path>
</manifestEntries>
</archive>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>

我正在使用 Spring ClassPathResource() 加载属性文件。下面显示了相同的代码片段:

 InputStream stream = new ClassPathResource(classPathConfigFilePath).getInputStream();
Proerties properties = new Properties();
properties.load(stream);

在运行时,它无法定位导致 FileNotFoundException 的属性文件。

谢谢。

最佳答案

默认情况下,Spring-Boot 在以下位置搜索 application.properties 文件

  1. 类路径根
  2. 当前目录
  3. 类路径/config
  4. /config 当前目录的子目录

所有这些文件(如果可用)都按该顺序加载,这意味着 1 的属性可以被 2、3、4 覆盖。所有加载的属性都可以作为 Environment 的一部分使用,因此可以在占位符中用于配置。

作为对上述加载规则的补充还有profile可以加载特定文件。对于给定的配置文件,它还将尝试加载 application-{profile}.properties。对于该特定文件,还会考虑上述加载规则。

所有加载的属性都可以通过 Environment 使用,这意味着可以通过 spring unified property management 使用.可以直接使用 Environment 来检索配置参数,也可以使用占位符和 @Value 注释进行配置

@Configuration
public class SomeConfigClass {
@Autowired
private Environment env;

public DataSource dataSource() {
SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setUsername(env.getProperty("jdbc.username"));
ds.setPassword(env.getProperty("jdbc.password"));
ds.setDriverClass(Driver.class);
ds.setUrl(env.getProperty("jdbc.url"));
return ds;
}
}

或者用@Value

 @Configuration
public class SomeConfigClass {

@Value("${jdbc.username}")
private String username;

@Value("${jdbc.password}")
private String password;

@Value("${jdbc.url}")
private String url


public DataSource dataSource() {
SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setUsername(username);
ds.setPassword(password);
ds.setDriverClass(Driver.class);
ds.setUrl(url);
return ds;
}
}

链接

  1. Spring Boot READ-ME
  2. Spring 框架简介 documentation
  3. Spring Property Managed blog
  4. Spring Boot Loader READ-ME

关于java - 使用spring boot loader WarLauncher时如何加载war文件之外的属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20418201/

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