【问题标题】:Spring - How to inject String value to constructor?Spring - 如何将字符串值注入构造函数?
【发布时间】:2020-01-02 19:52:57
【问题描述】:

我有以下组件:

@Component
public class ServiceManagerImpl implements ServiceManager {

  private final ServiceA serviceA;
  private final ServiceB serviceB;
  private final String path;

  @Autowired
  protected ServiceManagerImpl(ServiceA serviceA, ServiceB serviceB, String path) {
    this.serviceA= serviceA;
    this.serviceB= serviceB;
    this.path= path;
  }

(...)

}

现在我想创建一个简单的服务,我将在上面注入具有特定路径值的组件。该值应来自具有字符串常量的类:

@Component
public class ServiceManagerClientImpl implements ServiceManagerClient {

  private ServiceManager serviceManager;

  @Autowired
  public ServiceManagerClientImpl(ServiceManager serviceManager) {
    this.serviceManager = serviceManager;
  }
}

是否可以在 ServiceManagerClientImpl 级别动态注入简单的 path 值(不是来自属性/yaml 文件)?

【问题讨论】:

  • 它是一个有常量的类还是像application.properties这样的资源有关系吗?
  • 在 Spring Boot 中使用 Value 和 Qualifier 注解。
  • 您可以将其设置为环境变量并从中读取。
  • @SujayMohan 例子?
  • @duffymo 例子?

标签: java spring inversion-of-control code-injection


【解决方案1】:

您可以自动装配 Environment 类

import org.springframework.core.env.Environment;

@Autowired
private Environment environment;

您可以使用以下语句读取环境变量(在您的情况下为“路径”)。

environment.getProperty("path");

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多