@ConfigurationProperties 不使用 。YAML 文件

@ConfigurationProperties is not working with .YAML files

提问人:user2315104 提问时间:8/24/2018 最后编辑:user2315104 更新时间:7/7/2020 访问量:15128

问:

我是SpringBoot的新手,并尝试使用内置的SpringBoot注释从YML文件中读取属性。

代码如下:

应用属性.java

@Component
@ConfigurationProperties(prefix = "patterns")
public class AppProperties {

    private List<PasswordPattern> password_patterns = new ArrayList<>();

    public static class PasswordPattern {
        private String pattern1;

        @Autowired
        public String getPattern1() {
            return pattern1;
        }

        public void setPattern1(String pattern1) {
            this.pattern1 = pattern1;
        }
    }

}

调用 AppProperties 的测试类

测试1.java

public class Test1 {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        // TODO Auto-generated method stub

        AppProperties.PasswordPattern a = new AppProperties.PasswordPattern();

        System.out.println(a.getPattern1());
    }

}

application.yml 文件

--- 
patterns: 
  password_patterns: 
  pattern1: "test"

EXPECTATION:是 getPattern1() 方法应该返回从 yml 文件中读取的值

我为此类问题推荐了许多帖子,但不明白我犯了什么错误。我是否遗漏了任何特定的注释?我红了关于

@Autowired

它与依赖注入有关,我也使用过它...... 请提出建议

进一步编辑:

在关注“Alexander pinkin”的帖子后,出现以下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'patterns.password-patterns' to java.util.Map<ja
va.lang.String, java.lang.String>:

    Reason: No converter found capable of converting from type [java.lang.String
] to type [java.util.Map<java.lang.String, java.lang.String>]

Action:

Update your application's configuration

进一步编辑 2:

应用属性.java

@Component
@ConfigurationProperties(prefix = "patterns")
public class AppProperties {

    private List<Menu> menus = new ArrayList<>();

    public static class Menu {
        private String pattern1;

        public String getPattern1() {
            return pattern1;
        }

        public void setPattern1(String pattern1) {
            this.pattern1 = pattern1;
        }

    }
}

密码应用程序.java

@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class PasswordpatApplication {

    private static final Logger LOG = LoggerFactory.getLogger(PasswordpatApplication.class);

    @Autowired
    public static void main(String[] args) {
        SpringApplication.run(PasswordpatApplication.class, args);

        AppProperties.Menu a = new AppProperties.Menu();
        LOG.info("hi");
        LOG.info(a.getPattern1());

    }

应用程序.yml

patterns: 
  password-patterns: 
  pattern1: test

输出:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)

2018-08-24 18:56:21.116  INFO 11712 --- [           main] c.e.passwordpat.Passwo
rdpatApplication   : Starting PasswordpatApplication v0.0.1-SNAPSHOT on PUNITP13
0066L with PID 11712 (C:\Users\irfan.sayed\Downloads\passwordpat\target\password
pat-0.0.1-SNAPSHOT.jar started by irfan.sayed in C:\Users\irfan.sayed\Downloads\
passwordpat\target)
2018-08-24 18:56:21.131  INFO 11712 --- [           main] c.e.passwordpat.Passwo
rdpatApplication   : No active profile set, falling back to default profiles: de
fault
2018-08-24 18:56:21.271  INFO 11712 --- [           main] s.c.a.AnnotationConfig
ApplicationContext : Refreshing org.springframework.context.annotation.Annotatio
nConfigApplicationContext@6c629d6e: startup date [Fri Aug 24 18:56:21 IST 2018];
 root of context hierarchy
2018-08-24 18:56:22.066  WARN 11712 --- [           main] f.a.AutowiredAnnotatio
nBeanPostProcessor : Autowired annotation is not supported on static methods: pu
blic static void com.example.passwordpat.PasswordpatApplication.main(java.lang.S
tring[])
2018-08-24 18:56:23.887  INFO 11712 --- [           main] o.s.j.e.a.AnnotationMB
eanExporter        : Registering beans for JMX exposure on startup
2018-08-24 18:56:23.920  INFO 11712 --- [           main] c.e.passwordpat.Passwo
rdpatApplication   : Started PasswordpatApplication in 3.484 seconds (JVM runnin
g for 4.104)
2018-08-24 18:56:23.929  INFO 11712 --- [           main] c.e.passwordpat.Passwo
rdpatApplication   : hi
2018-08-24 18:56:23.931  INFO 11712 --- [           main] c.e.passwordpat.Passwo
rdpatApplication   : null
2018-08-24 18:56:23.938  INFO 11712 --- [       Thread-2] s.c.a.AnnotationConfig
ApplicationContext : Closing org.springframework.context.annotation.AnnotationCo
nfigApplicationContext@6c629d6e: startup date [Fri Aug 24 18:56:21 IST 2018]; ro
ot of context hierarchy
2018-08-24 18:56:23.946  INFO 11712 --- [       Thread-2] o.s.j.e.a.AnnotationMB
eanExporter        : Unregistering JMX-exposed beans on shutdown

现在,控制台上没有打印任何内容。既没有任何错误或异常

请提出建议

java spring-boot)

评论

0赞 Magnus 8/24/2018
在示例中,您从未启动过 spring 上下文,您需要启动一个 spring 上下文并从上下文中获取配置的实例。
0赞 user2315104 8/24/2018
谢谢你的评论。你能详细说明一下吗?任何示例示例?
0赞 chrylis -cautiouslyoptimistic- 8/24/2018
如果将字段名称更改为 ?(如果这不起作用,请将两者都更改为确切?password_patternspasswordPatternspasswordpatterns
0赞 Alien 8/24/2018
尝试从 pattern1: “test” 中删除引号,如下所示 pattern1: test
0赞 user2315104 8/24/2018
谢谢 Chrylis 和 Alien。我尝试了你的两个选项,但仍然为 null 即将到来

答:

0赞 Machhindra Neupane 8/24/2018 #1

您可以使用@Value注释 如果您的 YML 配置是

management:
 security:
  enabled: true

比您可以在@Configuration上使用

@Value("${management.security.enabled}")
bolean managementSecurityenabled;
1赞 Alien 8/24/2018 #2

看起来像它的缩进问题。只是为了确认,把任何其他直接属性

amazon:
associateId: habuma-20

如果成功,请尝试获取它,然后尝试使用如下。

patterns: 
  password_patterns: 
    pattern1: "test"

如果上述方法不起作用,请尝试从“test”中删除引号。

注意:避免使用制表符 http://yaml.org/faq.html

https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html

0赞 agackovka 8/24/2018 #3

首先,您应该修复缩进:

patterns: 
  password_patterns: 
  pattern1: "test"

patterns: 
  password_patterns: 
    pattern1: "test"

第二件需要注意的事情 - 你已经标记了你的属性类,所以以后可以在 spring 上下文中找到它(我也建议在这里使用它会更自然,因为它是一个配置),所以当你想将它与填充的配置属性一起使用时,你应该从上下文中获取它。 下一段代码将使您能够在 Bean 中使用配置数据:@Component@Configuration

@Autowired
private AppProperties appProperties;

第三件事 - 确保在文件的某个地方有注释@Configuration@EnableConfigurationProperties

此外,在窄标记下使用整个 AppProperties 类也不明显......patterns

1赞 Alexander Pankin 8/24/2018 #4

您应该启动 Spring 上下文并将您的属性命名为“password-patterns”或“passwordPatterns”。

这应该有效:

AppProperties.java:

@ConfigurationProperties(prefix = "patterns")
public class AppProperties {

    private Map<String, String> passwordPatterns = new HashMap<>();

    public Map<String, String> getPasswordPatterns() {
        return passwordPatterns;
    }
}

演示应用程序.java

@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class DemoApplication implements CommandLineRunner {
    private static final Logger LOG = LoggerFactory
            .getLogger(DemoApplication.class);

    @Autowired
    private AppProperties appProperties;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) {
        LOG.info("pattern = {}", appProperties.getPasswordPatterns().get("pattern1"));
    }
}

应用程序.yml

patterns:
  password-patterns:
    pattern1: "test"

评论

0赞 user2315104 8/24/2018
按照您的建议进行修改后,“mvn clean package”命令 failing.it 说,找不到主类
0赞 user2315104 8/24/2018
通过在代码中添加某些更改来编辑进一步的帖子。请提出建议
0赞 user2315104 8/27/2018
成功了。缺少@Component我的一个班级的注释。
0赞 Mert Sevinc 10/18/2023
我强烈建议将 getter 和 setter 放在 AppProperties 类中,否则它可能会失败。
0赞 Abdusoli 7/7/2020 #5

除了@Alexander Pankin 的答案之外,程序还可能要求您添加 pom.xmldependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>