2 回答
TA贡献1812条经验 获得超5个赞
我想出了一种不同的方法,它允许我非常直观地使用注入的服务。
使用构造函数注入的解决方案:
public abstract class FoodService {
protected RecipeService recipeService;
FoodService (RecipeService recipeService) {
this.recipeService = recipeService;
}
}
public class ItalianFoodService extends FoodService {
// Only needed if ItalianRecipeService holds additional methods.
@Inject @Italian ItalianRecipeService recipeService;
@Inject
ItalianFoodService(@Italian RecipeService recipeService) {
super(recipeService);
}
}
或者,也可以通过
使用@PostConstruct 的解决方案:
public abstract class FoodService {
protected RecipeService recipeService;
}
public class ItalianFoodService extends FoodService {
// Only needed if ItalianRecipeService holds additional methods.
@Inject @Italian ItalianRecipeService recipeService;
@PostConstruct
postConstruct() {
super.recipeService = recipeService;
}
}
两种解决方案都非常简短且可读,而具有构造函数注入的解决方案对注入的处理稍微更加明确。
添加回答
举报