ซึ่งโดยปกติแล้ว เวลาเราเขียนมักจะเป็น 1 interface ต่อ 1 implementation เมื่อต้องการเรียกใช้งาน service ใด เราก็จะเรียกผ่าน interface ของมันแทน ด้วยการ @Autowired interface นั้นๆ เข้ามา ในกรณีนี้ไม่มีปัญหาอะไร เพราะเป็นแบบ 1 : 1 แล้วถ้าเป็น 1 : M แบบนี้ล่ะ
//interface
public interface Service{
public Page findAllElementsByPaging(Pageable page);
}
//implementatoin
@Service("documentService")
@Transactional(propagation = Propagation.REQUIRED)
public class DocumentService implements Service{//********
@Override
public Page findAllElementsByPaging(Pageable page){
...
...
...
}
}
@Service("binaryService")
@Transactional(propagation = Propagation.REQUIRED)
public class BinaryService implements Service{//*********
@Override
public Page findAllElementsByPaging(Pageable page){
...
...
...
}
}
...
...
...
เราจะเห็นได้ว่า inteface Service นั้น ถูก implements ไปเป็น DocumentService กับ BinaryService ซึงเป็นแบบ 1 : Mถ้าเราต้องการเรียกใช้งาน Service ใด ในตอนที่ @Autowired Service นั้นให้เราระบุ implementation ที่ต้องการลงไปด้วย เพื่อที่จะได้ไม่ทำให้เกิดปัญหาเวลา run application เพราะ spring จะถือว่า Service คือ Singleton สามารถมีได้แค่อันเดียวเท่านั้น การเรียกใช้ ทำได้ดังนี้
...
...
...
@Autowired
@Qualifier("documentService")//********
private Service service; //service ตัวนี้ จะทำงานเป็น DocumentService
...
...
...
แค่นั้นก็เรียบร้อยโรงเรียนวัดศาลาลอยครับ ^_______________^
ขอบคุณครับ
ตอบลบ