代码之家  ›  专栏  ›  技术社区  ›  Itsik Mauyhas

Spring-将application.properties注入jar(作为Maven依赖项)

  •  0
  • Itsik Mauyhas  · 技术社区  · 6 年前

    我想从我创建并包含在pom中的jar访问application.properties文件。

    <dependency>
        <groupId>some.group.name</groupId>
        <artifactId>some-jar-name</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    

    在jar中,我有一个类需要父级的值 application.properties 文件。

    我已经试过了 spring.profiles.active spring.profiles.active=test 并打印JVM参数,但未注入值。

    public class PropertiesRepository  {
        //get application.properties
        public PropertiesRepository(String appName, String instance) {
            RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
            List<String> arguments = runtimeMxBean.getInputArguments();
    
            for (Iterator iterator = arguments.iterator(); iterator.hasNext();) {
                String param = (String) iterator.next();
                System.out.println("Runtime arg=" + param);
            }
        }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   LppEdd    6 年前

    类路径 ,使用 @Configuration 与…同班 @PropertySource

    @Configuration
    @PropertySource("classpath:your-file-name.properties")
    public class PropertiesConfiguration { }
    

    如果你的文件名是标准的 application.properties ,您甚至不需要这样做,它将自动拾取,并且您可以通过

    @Value("${your-property}")
    

    Environment#getProperty("your-property")
    

    考虑到你在 Spring Boot ,所有内容都应该与当前的依赖项配置完美配合。