【问题标题】:Spring Bean definition with value from application.yml具有来自 application.yml 的值的 Spring Bean 定义
【发布时间】:2022-11-22 20:22:10
【问题描述】:

我想定义一个应该由 Spring 管理并从 application.yml 注入其属性的 Bean。

application.yml //
client:
   port: 80
   address: "xyz.net"
   timeout: 100



Client.java // this class is external, we cannot change it
public class Client {
    private final int port;
    private final String address;
    public void setPortAddress(String address, int port) //
    ...
}

我确实尝试使用 @Configuration 但它不起作用。错误是地址未设置,同时尝试访问客户端实例。

Service.java //

@Configuration
@ConfigurationProperties(prefix="client")
@ComponentScan(basePackageClasses=Service.class)
public class Config {
   int port;
   String address;

   @Bean
   Client getClient(){
      Client client = new Client();
      client.setPortAddress(address, port);
      return client;
   }
} 

非常感谢任何帮助。

【问题讨论】:

  • 删除 @ConfigurationProperties 并将 @Value("${client.port} 等添加到字段中。要么是配置类,要么是属性持有者,您正试图将两者硬塞进一个类中。

标签: java spring javabeans code-injection


【解决方案1】:

看起来您还没有将 application.yml 文件映射到 Spring 对象。

实现此目的的一种方法是使用@ConfigurationProperties。你可以在这里了解更多关于它们的信息:https://www.baeldung.com/configuration-properties-in-spring-boot

对于您的示例,我建议如下:

要添加的新类:

@Configuration
@ConfigurationProperties(prefix = "client")
public class ClientProperties {
    
    private int port;
    private String address;

    // standard getters and setters
}

将其添加为 getClient() 方法的参数

@Configuration
public class Config {

   @Bean
   Client getClient(ClientProperties properties){
      Client client = new Client();
      client.setPortAddress(properties.getAddress(), properties.getPort());
      return client;
   }
} 

【讨论】:

  • 你将如何使用那个 Bean?我有类似 ApplicationContext context = new AnnotationApplictionContext(Config.class); Client client = context.getBean("client", Client.class).... 它不起作用并向我显示错误,该地址未设置!
猜你喜欢
  • 2014-11-23
  • 1970-01-01
  • 2020-01-09
  • 2023-04-01
  • 2012-06-08
  • 2021-02-25
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多