Hi,大家好,我是一個愛冒泡的程序猿
有事情耽擱的好幾天沒更新了,每日一更計劃又泡湯了(灬ꈍ ꈍ灬)
小編今天最近遇到的一個問題就是,有一個水果的Service,它的實現類中,同樣方法名的有兩個,一個是“榴蓮”,一個是“蘋果”(萬一榴蓮壞了,還有蘋果吃٩(๑❛ᴗ❛๑)۶),如何優雅的決定它的出現。
有幾個解決方法,順序:從差到優~
方法一:
由於“榴蓮”和“蘋果”都在這個實現類裏,方法名相同,所以只能把一方先注掉
這個方法最爛也最不友好,小編是由於忙於開發,就先這樣跳過去了做其他的了,大家不要學我(´•༝•`)
優點:只是實現需求,無任何優點可言,無任何美感可言
缺點:每次都得手動改代碼,想吃“榴蓮”,得把“蘋果”註釋掉,反之
方法二:
在方法一的基礎上,把水果的service實現類拆分爲兩個,一個是“榴蓮”實現類,一個是“蘋果”實現類
在Controller中 注入service,通過註解 @Autowire + @Qualifier實現,具體代碼如下:
Controller
@Autowired
@Qualifier("durian")
private FruitService fruitService;
Service
/**
* Created by git on 2020/4/21.
*
* @author Emelia
*/
public interface FruitService {
String getFruit();
}
“榴蓮”實現類
/**
* 榴蓮
*
* @author Emelia
*/
@Service("durian")
@Slf4j
public class durianServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "榴蓮";
return fruit;
}
}
“蘋果”實現類
/**
* 蘋果
*
* @author Emelia
*/
@Service("apple")
@Slf4j
public class appleServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "蘋果";
return fruit;
}
}
優點:在controller中修改@Qualifier的值就可以變化
缺點:還是得手動修改代碼內容,一個Controller調用還好,如果有多個Controller調用就都得相應的更改
方法三:
和方法二差不多,只不過在Controller注入的時候使用註解@Resource 替換了 @Autowire + @Qualifier實現,具體代碼如下:
Controller
@Resource("durian")
private FruitService fruitService;
Service
/**
* Created by git on 2020/4/21.
*
* @author Emelia
*/
public interface FruitService {
String getFruit();
}
“榴蓮”實現類
/**
* 榴蓮
*
* @author Emelia
*/
@Service("durian")
@Slf4j
public class durianServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "榴蓮";
return fruit;
}
}
“蘋果”實現類
/**
* 蘋果
*
* @author Emelia
*/
@Service("apple")
@Slf4j
public class appleServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "蘋果";
return fruit;
}
}
優點:在controller中修改@Resource 的值就可以變化
缺點:還是得手動修改代碼內容,一個Controller調用還好,如果有多個Controller調用就都得相應的更改
方法四:
通過配置文件動態配置,實現類中只需要用 @Configuration+@ConditionalOnProperty
不需要@Service ,這兩個註解也可以注入Service,具體代碼如下:
application.yml
fruit:
impl: apple
Controller
@Autowired
private FruitService fruitService;
Service
/**
* Created by git on 2020/4/21.
*
* @author Emelia
*/
public interface FruitService {
String getFruit();
}
“榴蓮”實現類
/**
* 榴蓮
*
* @author Emelia
*/
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "fruit", name = "impl", havingValue = "durian")
public class durianServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "榴蓮";
return fruit;
}
}
“蘋果”實現類
/**
* 蘋果
*
* @author Emelia
*/
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "fruit", name = "impl", havingValue = "apple")
public class appleServiceImpl implements FruitService {
@Override
public String getFruit() {
String fruit = "蘋果";
return fruit;
}
}
優點:只需要修改配置就可以決定使用哪個實現類,如此甚好,也不需要額外的配置文件,優雅的很
缺點:好用,暫時沒發現缺點
參考文章:
https://blog.csdn.net/mengxiangxingdong/article/details/87919315
可能是我第一次使用這個註解,真香啊(•̀∀•́)棒
如果有更好的方式,歡迎大家前來踢館~掰掰~ 奔向阿里的第7天