是否可以从spring应用程序属性中获取自定义对象? [英] Is it possible to get custom object from spring application properties?

查看:111
本文介绍了是否可以从spring应用程序属性中获取自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从application.yaml获取自己的对象并将其与@Value绑定到我的组件?

Is it possible to get own object from application.yaml and bind it with @Value to my component?

模型:

@Data
public class CurrencyPlan {
    private String id;
    private String basePrice;
    private String merchantId;
}

application.yml:

application.yml:

plans:
  eur:
    id: id
    basePrice: 5
    merchantId: someid

我正在尝试做什么:

@Value("${plans.eur}") CurrencyPlan eurPlan

我得到的:

java.lang.IllegalArgumentException: Could not resolve placeholder 'plans.eur' in value "${plans.eur}"

这甚至可能吗?如果是这样,该怎么做?我的想法很不错:(

Is this even possible? And if so, how to do it? I'm pretty out of ideas :(

提前致谢;)

推荐答案

如果您希望将属性绑定到类,可以使用 @ConfigurationProperties

If you're looking to bind your properties to a class you can use @ConfigurationProperties.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration -properties

@ConfigurationProperties(prefix =plans.eur)
@Component 将被放置在 CurrencyPlan 上。 @EnableConfigurationProperties 最好放在 @Configuration 类上。

@ConfigurationProperties(prefix="plans.eur") and @Component would be placed on the CurrencyPlan. @EnableConfigurationProperties preferably placed on an @Configuration class.

您可以将 CurrencyPlan 类自动装入依赖类中。

After you can autowire the CurrencyPlan class into the dependent classes.

这篇关于是否可以从spring应用程序属性中获取自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆