Home > Net >  Autowiring Enums in Spring boot
Autowiring Enums in Spring boot

Time:12-24

In my SpringBoot App I have class:

@Service
public enum LockerRepo {
    INSTANCE;

    private static List<Locker> lockerList = new ArrayList<>(generateExampleData());
    
    private static List<Locker> generateExampleData() {

        List<Locker> exampleList = new ArrayList<>();

            for (int i = 0; i < 100; i  ) {
                if (i <= 30) {
                    exampleList.add(new Locker(i, Size.S));
                } else if (1 > 30 && i <= 70) {
                    exampleList.add(new Locker(i, Size.M));
                } else {
                    exampleList.add(new Locker(i, Size.L));
                }
            }

        return exampleList;
    }

    public static LockerRepo getInstance() {
        return INSTANCE;
    }
}

And I'm getting error:

***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.smartlocker.repository.LockerRepo required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.

I have it autowired in other classes, and also called by getInstance() method. I was trying to add different annotations, and it didn't worked out. Also in test module it works well, and I can access it by getInstance()

CodePudding user response:

As I wrote as comment, Enums cannot be used as Spring beans because they cannot be instantiated using the default constructor.

But if you still have to use the @Service annotation and also @Autowired to inject your class, you use the Singleton Pattern:

@Service
public class LockerRepo {

    private static final LockerRepo INSTANCE = new LockerRepo();

    private List<Locker> lockerList;

    private LockerRepo() {
        lockerList = generateExampleData();
    }

    private List<Locker> generateExampleData() {
        List<Locker> exampleList = new ArrayList<>();

        for (int i = 0; i < 100; i  ) {
            if (i <= 30) {
                exampleList.add(new Locker(i, Size.S));
            } else if (1 > 30 && i <= 70) {
                exampleList.add(new Locker(i, Size.M));
            } else {
                exampleList.add(new Locker(i, Size.L));
            }
        }

        return exampleList;
    }

    public static LockerRepo getInstance() {
        return INSTANCE;
    }

    // getter for locker list
}

This should work, but it has a disadvantage - it makes your code more difficult to test and you have also tight coupling between your components. So it is generally not recommented as best practice.

  • Related