简体   繁体   English

无法使用Spring的@Value,@ ConfigurationProperties注释从Properties文件中检索值

[英]Unable to retrieve value from Properties file using Spring's @Value, @ConfigurationProperties annotations

I am new to Spring Boot and using Spring Annotations. 我是Spring Boot新手并使用Spring Annotations。 I am trying to build a sample spring boot application in which I get a value for my java property using the properties file. 我正在尝试构建一个示例Spring启动应用程序,在该应用程序中,我使用属性文件获取了我的java属性的值。 I am trying to use @Component & @ConfigurationProperties parameter. 我正在尝试使用@Component@ConfigurationProperties参数。 I followed a bunch of tutorials online and this StackOverflow article helped, but my property value is still null 我在线跟踪了一堆教程,这篇StackOverflow文章有所帮助,但我的属性值仍为null

Here is my code. 这是我的代码。

Looked through:- 看着: -

  1. unable to read properties using configurationproperties annotation 无法使用configurationproperties批注读取属性

  2. https://www.mkyong.com/spring/spring-propertysources-example/ https://www.mkyong.com/spring/spring-propertysources-example/

My SpringBoot Application class 我的SpringBoot应用程序类


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@EnableAutoConfiguration
@SpringBootApplication
public class Main {


  public static void main(String[] args) {
    ApplicationContext context =   SpringApplication.run(Main.class, args);
    TestConf t = context.getBean(TestConf.class);
    System.out.println(t.toString());
  }
}

TestConf Class TestConf类


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("pres")
public class TestConf {

  private String firstName;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public TestConf()
  {
    System.out.println("inside constructor");
    System.out.println("first name:" + firstName);
  }


  public static void main(String[] args){
    TestConf t = new TestConf();
  }

  @Override
  public String toString() {
    return "firstName:" + firstName;
  }
}

application.properties application.properties

pres.firstName=JACQUELYN

lastly my pom.xml 最后我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>phil</groupId>
  <artifactId>springTuit</artifactId>
  <version>1.0-SNAPSHOT</version>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
  </parent>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- Optional, for bootstrap -->
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>4.3.1</version>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <!-- Package as an executable jar/war -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.0</version>
      </plugin>
    </plugins>
  </build>

</project>

What is missing to retrieve the value from application.properties correctly into firstName? application.properties的值正确检索到firstName中缺少什么? Does it matter where my application.properties file lies? 我的application.properties文件位于何处? Although it is in its traditional spot under src/main/resources and my java files are under src/main/java 虽然它在src/main/resources下的传统位置,但我的java文件在src/main/java

Code needs couple of minor changes: 代码需要几个小的改动:

@Component
@ConfigurationProperties("classpath:application.properties")
public class TestConf {

  @Value("pres.firstName")
  private String firstName;

This seems standard. 这似乎是标准的。 However, you can try with the combination 但是,您可以尝试使用该组合

@Component
@PropertySource("classpath:applciation.properties") 
@ConfigurationProperties 

to TestConf.Java TestConf.Java

You have two fundamental problems: 你有两个基本问题:

  1. Your new TestConf() instance isn't a Spring-managed object and thus doesn't get injected at all. 您的new TestConf()实例不是Spring管理的对象,因此根本不会注入。

  2. Setter (or field) injection inherently means that the values aren't set until after the constructor runs. Setter(或field)注入本身意味着在构造函数运行之后才会设置值。

If you want to use a Spring bean from some task that gets run when you launch your Boot application, use a CommandLineRunner and inject the bean, preferably with constructor injection. 如果要从启动Boot应用程序时运行的某个任务中使用Spring bean,请使用CommandLineRunner并注入bean,最好使用构造函数注入。

you can try with the combination..it will work.... 你可以试试这个组合......它会起作用....

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "pres")
@Data
public class TestConf {

  private String firstName;

.............

}

You can use @Value to get a property's value or as you are trying to fetch the configs using a Configuration class, below example might be helpful. 您可以使用@Value获取属性的值,或者在尝试使用Configuration类获取配置时,下面的示例可能会有所帮助。

A Controller class: 一个Controller类:

@RestController
public class ConfigurationController {

//@Value("${app.name:Movies}") 
//private String name;
//Alternative of configuration class

@Autowired
private Configuration configuration;

@GetMapping("/config")
public MovieConfiguration retrieveConfiguration() {

    return new MovieConfiguration(configuration.getName());
}

A Pojo class Pojo课程

public class MovieConfiguration {

private String name;

public MovieConfiguration(String name) {
    this.name=name;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}}

A Configuration class 配置类

@Component
@ConfigurationProperties("app")
public class Configuration {

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}}

Properties 属性

server.port=8091
app.name=SpaceDrama

So it seemed like the reason I did not get my value was not because of the code, but because the port was in use. 所以看起来我没有得到我的价值的原因不是因为代码,而是因为端口正在使用中。 I thought should not be an issue, but turned out that once I killed the process using the port and ran my application there, everything worked as expected. 我认为不应该是一个问题,但事实证明,一旦我使用端口杀死进程并在那里运行我的应用程序,一切都按预期工作。 So my code was correct to begin with.. 所以我的代码开头是正确的..

Thanks for your answers stackoverflow community 感谢您的回答stackoverflow社区

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在春季使用自动装配从属性文件中检索键的值 - How to retrieve the value of a key from properties file in spring using Autowiring Spring - 使用注释设置属性值而不使用属性文件 - Spring - Set property value using annotations without using properties file 如何使用Spring注释将Properties文件中的值注入到现有实例(不受Spring管理)的字段中? - How do I inject a value from Properties file to a field of an existing instance (not managed by Spring) using Spring annotations? Spring ConfigurationProperties 文件 - 提供默认值 - Spring ConfigurationProperties file - giving a default value Spring 使用@ConfigurationProperties 和@Value 注入值 - Spring Inject Values with @ConfigurationProperties and @Value Spring Boot使用ConfigurationProperties从.properties和.yaml注入Map值 - Spring Boot injecting Map values from .properties and .yaml using ConfigurationProperties 无法使用@ConfigurationProperties将映射与来自spring boot yaml文件的复杂键绑定 - Unable to bind map with complex key from spring boot yaml file using @ConfigurationProperties 如何在Spring中使用@ConfigurationProperties加载Name Value属性 - How to load Name Value property using @ConfigurationProperties in Spring 基本测试类中的@Value注释不从属性文件中注入值 - @Value annotations in base test class not injecting values from properties file 如何使用.properties文件中的值初始化spring bean中的集合 - How to initialize a set in a spring bean using value from .properties file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM