Home > Back-end >  Prevent multiple bean instantiation on inheritance
Prevent multiple bean instantiation on inheritance

Time:01-30

I have the following problem I'm trying to overcome:

I have a Spring base component:

@Service
public class Circle {
...
  @Autowired
  public Circle() {
     loadFromDB();
  }
...
}

I have another component which inherits it:

@Service
public class BlueCircle extends Circle {
...
}

The problem here is loadFromDB is called twice because Spring instantiate Circle two times: first time when it "discovers" class Circle and a second time because of the inheritance.

Is there a "Spring" way to avoid this?

CodePudding user response:

IMHO a service extending another service is never a good approach. I would rather suggest you to create a service interface and then make your two services implementing that interface. In this way you should not have anymore this problem because you would call loadFromDB() only in one of your service.

CodePudding user response:

If you only need instance of BlueCircle then you might have to remove @Service on Circle class.

  •  Tags:  
  • Related