猿问

Spring Annotation Configs - 基于 YAML 配置动态创建类

我是 Spring 注释的新手。

我有以下 YAML 配置:

configLists: 
  - listItem1
  - listItem2mainConfig:
  listItem1:
    listingName: listItem1
    property1: testing-value-1
    property2: testing-value-2
    storageprop: example/storage/loc-2
  listItem2:
    listingName: listItem2
    property1: testing-value-1
    property2: testing-value-2
    storageprop: example/storage/loc-2

在 Spring Annotations 和配置的帮助下,我想动态地创建类。即由于在 mainConfig listItem1 和 listItem2 下有两个配置,因此应用程序应仅在单个类的帮助下创建两个实例。

如何在 Spring Boot 应用程序中使用 @Bean、@Configuration 和其他注解?

是否可以在创建实例时将运行时的配置传递给类?

对此的任何帮助表示赞赏。

谢谢,

阿维纳什·德什穆赫


慕姐4208626
浏览 146回答 1
1回答

慕桂英3389331

您可以执行以下操作:创建一个简单的 bean 类,注释@ConfigurationProperties如下:@Component@ConfigurationProperties("mainConfig")public class AppProperties {&nbsp; private Map<String, ListItem> listItems;&nbsp; public static class ListItem {&nbsp; &nbsp; private String listingName;&nbsp; &nbsp; private String property1;&nbsp; &nbsp; private String property2;&nbsp; &nbsp; private String storageProp;&nbsp; &nbsp; // setters, getters&nbsp; }&nbsp; // setters, getters}现在,我假设您只想通过可能注入它来访问代码中不同的“listItem”属性。在配置类中创建 bean:@Configurationclass AppConfiguration {&nbsp; @Autowired&nbsp; private AppProperties appProperties;&nbsp; @Bean("listItem1")&nbsp; public ListItem useListItem1() {&nbsp; &nbsp; return appProperties.getListItems().get("listItem1");&nbsp; }&nbsp; @Bean("listItem2")&nbsp; public ListItem useListItem2() {&nbsp; &nbsp; return appProperties.getListItems().get("listItem2");&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答