简体   繁体   中英

What's the best practice to autowire an hierarchy class?

Suppose I have below classes:

interface MyInterface<T>{}

class SomeClassA implements MyInterface<A> {}

I have a few options to autowire my ClassA object.

first:

@Service
class MyService {
  MyInterface<A> classA;

  MyService(MyInterface<A> classA) {
    this.classA = classA;
  }
}

second:

@Service
class MyService {
  MyInterface<A> classA;

  MyService(ClassA classA) {
    this.classA = classA;
  }
}

third:

@Service
class MyService {
  ClassA classA;

  MyService(ClassA classA) {
    this.classA = classA;
  }
}

What are the pros/cons of each implementation? Which one is the best practice?

I would say if there is a high possibility for class to have few different implementations use interface, if not use class. I would start with class only and start using interface when there is actual need for it. That would help with readability.

what ever makes you fast at this moment, and keeps you fast in the future without a noticeable energy losses :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM