0

I want to autowired service in enum like following code.

public enum TopupChargeService {
TYPE1{
    public Response fun() {
        return new ServiceRepo().getService().func1();
    }
},
TYPE2{
    public Response fun() {
        return new ServiceRepo().getService().func2();
    }
};
public abstract Response fun();
@Component
public static class ServiceRepo {
    private Service service;
    public Service getService() {
        return service ;
    }
    public ServiceRepo () {
        service = new ServiceImpl();
    }
 }
}

and Service code is like following code.

@Service
 public class ServiceImpl implements Service {

   @Autowired
   private RestTempalte restTemplate;

   Response fun1(){
     // use restTemplate in this fun 
   }

   Response fun2(){
     // use restTemplate in this fun 
   }

}

Also I defined restTemplate as bean in config class. But restTemplate is null.

My questions: 1- Is it correct way to call services? 2- Why restTemplate is null?

Emil
  • 423
  • 1
  • 12
  • 34
  • are you using spring-boot? if so which version or spring MVC, for spring boot it will work automatically if you use spring mvc use this @Bean public RestTemplate restTemplate() { return new RestTemplate(); } – Ashok Kumar N Aug 13 '18 at 08:47
  • Check this out : https://stackoverflow.com/questions/24213823/anyway-to-inject-autowire-an-inner-class-into-an-outer-class – dbl Aug 13 '18 at 08:47
  • 2
    it's incorrect, you have your `ServiceRepo` as a component, and you call `new ServiceRepo()` manually 2 times – Andrew Tobilko Aug 13 '18 at 08:48

1 Answers1

2
new ServiceRepo()

You are creating repository with constructor, that's why Spring cannot inject anything to this instance. In order to create the bean properly try to use ApplicationContext to create bean instances.

Also, I'd recommend that you do not use enums for this case. Enumerations are more like static constants and they should not bring behavior. Consider replacing this enum with Spring bean.

jreznot
  • 2,694
  • 2
  • 35
  • 53
  • Thanks for your answer. in fact my issue is like [this](https://softwareengineering.stackexchange.com/questions/343534/what-is-the-better-way-to-escape-from-too-many-if-else-if-from-the-following-cod) – Emil Aug 13 '18 at 10:02