Java 从 application.properties Spring Boot 读取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45428826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:01:43  来源:igfitidea点击:

Reading values from application.properties Spring Boot

javaspringspring-mvc

提问by Karan

My Spring boot app has this application structure:

我的 Spring Boot 应用程序具有以下应用程序结构:

  • src
    • main
      • java
      • resources
        • application.properties
  • 源文件
    • 主要的
      • 爪哇
      • 资源
        • 应用程序属性

This is my application.properties file:

这是我的 application.properties 文件:

logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java

I have a class which requires the use of that language=java property. This is how I am trying to use it:

我有一个需要使用该 language=java 属性的类。这就是我尝试使用它的方式:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

That printed value is always "null"for some reason! I have also tried putting this on top of the class declaration:

由于某种原因,该打印值始终为“空”!我也试过把它放在类声明的顶部:

@PropertySource(value = "classpath:application.properties")

回答by Barath

Missing stereotype annotation on top of class

缺少类顶部的构造型注释

@Component
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

回答by Mayank Sharma

you can try to use @PropertySourceand give it the path to property file, you can find the sample below:

您可以尝试使用@PropertySource并为其指定属性文件的路径,您可以在下面找到示例:

@Component
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

回答by Ognjen Mi?i?

Probably not the exact solution you're looking for, but you can also declare a property source bean:

可能不是您正在寻找的确切解决方案,但您也可以声明一个属性源 bean:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

回答by Anil Kumar Athuluri

It can be achieved in multiple ways, refer below.

它可以通过多种方式实现,请参阅下文。

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

OR

或者

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

回答by Karan

OK I figured it out with acts of desperation. I added the

好吧,我用绝望的行为想通了。我添加了

@PropertySource("classpath:application.properties") 

attribute but it still wasn't working for some reason.

属性,但由于某种原因它仍然不起作用。

I then deleted the "static" modifier and it worked!

然后我删除了“静态”修饰符,它起作用了!

I am not sure why it works without "static" being there but it does. If can explain it to me that would be wonderful because this is all confusing.

我不确定为什么它在没有“静态”的情况下工作,但确实如此。如果可以向我解释它会很棒,因为这一切都令人困惑。

回答by Mayank Madhav

Sometimes, the classpath entry for src/main/resourcescontains an exclude tag. If application.propertiesis present in this list of excluded items then @PropertySource("classpath:application.properties")will not be able to find the property file.

有时, 的类路径条目src/main/resources包含排除标记。如果application.properties出现在此排除项目列表中,@PropertySource("classpath:application.properties")则将无法找到属性文件。

Either remove the exclude entry from [.classpath][1]file for src/main/resourcesmanually, or use the Configure build path option in Eclipse and go to Source tab. Then remove the exclude entry from src.

手动从[.classpath][1]文件中删除排除条目src/main/resources,或使用 Eclipse 中的配置构建路径选项并转到源选项卡。然后从 中删除排除条目src

回答by BazSTR

create you beans

为你创造豆子

@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationBeansConfig {

    @Autowired
    Environment env;

    @Bean
    public IApplicationBeanService getService(){
        return new ApplicationBeansService(env);
    }
}

and then in service costructor

然后在服务构造函数中

@Service
public class ApplicationBeansService implements IApplicationBeanService {
...
   public ApplicationBeansService(Environment env){
      ...
      String value = env.getProperty("your.value")
      ...
   }
...
}

don't forget fill your application.properties:

不要忘记填写您的 application.properties:

your.value = some-string-value

回答by Anindya Mukherjee

If you are using Spring boot you do not need @PropertySource("classpath:application.properties")if you are using spring boot starter parent , just remove the statickeyword and it should start working.

如果您使用的是 Spring boot,@PropertySource("classpath:application.properties")如果您使用的是 spring boot starter parent ,则不需要,只需删除static关键字,它就会开始工作。

回答by hello_earth

in my case, the same problem had a slightly different cause - i had a class with a static instance variable (the old usual way we used to implement a Singleton pattern), into which i wanted to inject an entry from application.properties (probably the "static" thing was why the property could not be found - with no errors no anything :/).

在我的例子中,同样的问题有一个稍微不同的原因 - 我有一个带有静态实例变量的类(我们用来实现单例模式的旧常用方法),我想从 application.properties 注入一个条目(可能是“静态”的事情是为什么找不到属性 - 没有错误没有任何东西:/)。

moreover this class was in a totally different package from the class declared as @SpringBootApplication. i understood that package names and locations have to be taken into serious consideration with Spring Boot and automatic component scanning. my 5 cent

此外,这个类与声明为@SpringBootApplication 的类在一个完全不同的包中。我知道使用 Spring Boot 和自动组件扫描必须认真考虑包名称和位置。我的 5 美分

回答by VC2019

As provided in the 2nd answer above I was indeed using the spring boot, so removed the static keyword and that resolved my issue. Make sure you don't have static for the property defined with @Value.

正如上面的第二个答案中提供的那样,我确实使用了弹簧靴,因此删除了 static 关键字并解决了我的问题。确保您没有使用 @Value 定义的属性的静态。