【问题标题】:spring force fields initialization弹簧力场初始化
【发布时间】:2016-09-06 12:36:54
【问题描述】:

我们如何将以下对象转换为 spring bean 以便我们可以保留确切的功能?通过功能,我试图专注于构造函数初始化。

class RealObject {
    private String f1;
    private String f2;
    private String f3;
    private int f4;
    private int f5;

    public RealObject(String f1, String f2, String f3, int f4, int f5) {
        this.f1 = f1;
        this.f2 = f2;
        this.f3 = f3;
        this.f4 = f4;
        this.f5 = f5;
    }

    ... getters ...
}

spring bean 的样子

@Bean
class RealObject {
    private String f1;
    private String f2;
    private String f3;
    private int f4;
    private int f5;

    ... getters ...
}

这个 bean 的问题是它永远不会强迫我在我的对象中提供我需要的参数。我可以为每个输入做一些手动检查,但如果你有太多......它根本不会优雅。

我有什么解决方案?

稍后编辑:我需要在运行时传递值。

【问题讨论】:

  • 因为您使用 Spring(或任何 DI 解决方案)并不意味着一切都必须是托管 bean。为什么你需要这个类由 spring 管理?

标签: java spring


【解决方案1】:

你可以在构造函数上同时使用@Autowired@Value

@Autowired
public RealObject(@Value("#{property.f1}") String f1, 
                  @Value("#{property.f2}") String f2, 
                  ... ) {

}

在这种情况下,您需要一个外部属性来将值分配给f1f2...

【讨论】:

  • 我不想从属性中获取值。我需要在运行时以某种方式传递它们。
  • 你不能用字符串。您可以创建一个包含所有这些字符串的对象并注入该对象。
  • 另外。如果需要在运行时传递,为什么需要通过spring实例化对象?
  • 我需要在对象中注入一个服务,我还需要设置一些东西(比如一个 init 函数)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多