Home > Software engineering >  How can I autowire a list of beans as unmodifiable?
How can I autowire a list of beans as unmodifiable?

Time:02-25

I successfully autowired a list of beans like this.


@Autowire
private final List<SpecificType> beans;

How can I make it unmodifiable? More specifically, How can I get autowired with an unmodifiable list?

CodePudding user response:

You can use constructor injection and do something like this:

@Component
public class ComponentClass {

    private final List<SpecificType> beans;

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

CodePudding user response:

Instead of using this:

@Autowire
private final List<SpecificType> beans;

Use the class constructor to receive the list and make it immutable.

@Component
public YourClass{

   private final List<SpecificType> beans;

   public YourClass(List<SpecificType> beans){

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