爲解決移植性問題而設計的
一開始大多數項目都是直接在業務處理層的Service類中嵌入JDBC代碼,這就使得這個Service類與數據庫緊藕合,在換一種數據庫後,就要修改Service類中的sql。於是就有了controller+service+serviceImpl; Service類設計成一個接口,使控制層只依賴這個接口;這樣,當某天這個應用要跑在其它數據庫上時,就而只需要增加一個serviceImpl類。
項目結構如下:
具體代碼如下:
PersonService
package com.service.serviceimpldemo.Service;
/**
* description:
* author:
*/
public interface PersonService {
public String name();
}
WomanServiceImpl
package com.service.serviceimpldemo.Service.impl;
import com.service.serviceimpldemo.Service.PersonService;
import org.springframework.stereotype.Service;
/**
* description:
* author:
*/
@Service("womanService")
public class WomanServiceImpl implements PersonService {
@Override
public String name(){
return "Woman";
}
}
ManServiceImpl
package com.service.serviceimpldemo.Service.impl;
import com.service.serviceimpldemo.Service.PersonService;
import org.springframework.stereotype.Service;
/**
* description:
* author:
*/
@Service("manService")
public class ManServiceImpl implements PersonService {
@Override
public String name(){
return "Man";
}
}
PersonController
package com.service.serviceimpldemo.Controller;
import com.service.serviceimpldemo.Service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* description:
* author:
*/
@RestController
public class PersonController {
@Autowired
//如果該Service有多個實現類,設置注入哪個ServiceImpl類
@Qualifier("womanService")
private PersonService personService;
@RequestMapping("/name.do")
public String name(){
return personService.name();
}
}