【问题标题】:Where to package properties file in Spring Boot war file?Spring Boot 战争文件中的属性文件在哪里打包?
【发布时间】:2023-04-04 01:25:02
【问题描述】:

我有一个控制器文件如下:

@Controller
@PropertySource("file:config/code.properties")
public class ActionController {
    //...

我想把它打包成一个war文件。 config 文件夹应该位于项目结构中的什么位置?

【问题讨论】:

    标签: spring-boot war directory-structure properties-file


    【解决方案1】:

    如果您使用的是 springboot ,您可以将所有资源(如属性文件等)放在您的 resources (src/main/resources) 文件夹下,它将出现在创建的 jar 或 war 中。

    SpringApplication 从 application.properties 文件加载属性 在以下位置并将它们添加到 Spring 环境中:

    当前目录的/config 子目录。 当前目录。 类路径 /config 包。 类路径根目录。

    您也可以使用以下命令行参数自己指定路径,例如,如果您希望文件出现在战争之外的外部:

    --spring.config.location=${workspace_loc:/YOURPROYECTNAME}/src/main/resources/
    
    $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
    

    请阅读Official Doc

    如何使用属性文件,一种方法是:

    @Configuration
    @Profile("code")
    @PropertySource("file:/{selected location}/code.properties")
    public class CodeTestClass {
    
        @Autowired
        Environment env;
    
        @Bean
        public boolean test() {
            System.out.println(env.getProperty("code.test"));
            return true;
        }
    }
    

    【讨论】:

    • 因此,假设我的 src/main/resources 当前包含一个 static 文件夹和一个 templates 文件夹,那么我的 config 文件夹应该与这两个其他文件夹处于同一级别?
    • 是的,如果你的application.properties在同一级别src/main/resources默认会自动复制到war中。
    • 那是我放它们的地方,但我仍然收到此错误:Caused by: java.io.FileNotFoundException: config/code.properties (No such file or directory)
    • 哦,你已经将application.properties名称更改为code.properties,在这种情况下,你必须使用spring.config.name将属性文件名设置为code,这样springboot才会知道更改文件名。
    • 不,我还有 application.properties。这是一个单独的配置文件
    猜你喜欢
    • 2019-08-28
    • 2011-03-22
    • 1970-01-01
    • 2020-01-13
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2011-07-06
    相关资源
    最近更新 更多