[SOLVED] How to Autowire Spring Bean for Enum in Java – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by zeus

How can I avoid creating new objects by using spring configuration @Bean for Enums

Example in below enum E how can I avoid new A() and new B() object creation using spring configuration Beans.

public enum E {

    FIRST(new A()),     // How to avoid creating new objects using Spring beans
    SECOND(new B());    

    private final I i;

    E(I arg){
        this.i = arg;
    }

    public static someMethod(){};
}
public interface I{
    int method(){}
}
public class A implements I {

    @Override
    public int method(){}
}

public class B implements I {

    @Override
    public int method(){}
}



Solution

I implemented it in the following way.

public enum E {

    FIRST(SpringContext.getBean(A.class)),     // How to avoid creating new objects using Spring beans
    SECOND(SpringContext.getBean(B.class));

    private final I i;
    
    <T extends Object> BulkUploadType(T bean) {
        this.i = (I) bean;
    }

    E(I arg){
        this.i = arg;
    }

    public static someMethod(){};
}

The getBean method will return you the Bean of the implemented class.

public static <T extends Object> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }


This Question was asked in StackOverflow by zeus and Answered by Vikash It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?