我怎样才能自动装配一个不可修改的bean列表?

How can I autowire a list of beans as unmodifiable?

我成功地自动装配了一个像这样的 bean 列表。


@Autowire
private final List<SpecificType> beans;

如何让它不可修改? 更具体地说,如何使用不可修改的列表自动装配?

您可以使用构造函数注入并执行如下操作:

@Component
public class ComponentClass {

    private final List<SpecificType> beans;

    public ComponentClass(List<SpecificType> beans) {
        this.beans = Collections.unmodifiableList(beans);
    }
}

而不是使用这个:

@Autowire
private final List<SpecificType> beans;

使用 class 构造函数接收列表并使其不可变。

@Component
public YourClass{

   private final List<SpecificType> beans;

   public YourClass(List<SpecificType> beans){

      this.bean = Collections.unmodifiableList(beans);
   }
}