【问题标题】:How to use Guice or Spring to inject a list of objects based on properties如何使用 Guice 或 Spring 根据属性注入对象列表
【发布时间】:2016-09-22 05:12:42
【问题描述】:

我有一个像下面这样的课程。

public class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

我的意图是将List<Person> 注入另一个类,在该类中应该从属性文件创建列表。 像这样。

persons(0)=John
persons(1)=Jake

【问题讨论】:

  • Java 配置。注释。
  • 非常具体的要求。看起来您必须编写很多自定义代码。你有吗?

标签: java spring dependency-injection guice


【解决方案1】:

这里有 Spring 示例。 尝试这样,您可以添加任意数量的属性。或者只是遍历属性。在属性文件中只需设置属性person=Name。如果属性文件在项目资源文件中,那么 Spring 会自动找到它。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyProperties {

    @Value("${person}")
    private String person;

    public String getPerson(){
    return this.person;
    } 

}

public class anotherClass {

@Atowired
MyProperties myProperties;

List<Person> createObjectsBasingOnProperties(){
   ArrayList<Person> persons = new ArrayList<>();
   persons.add(new Person(myProperties.getPerson()));
   return persons;  

}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 2012-04-04
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2022-01-11
    相关资源
    最近更新 更多