我想爲所有控制器調用一個公共服務來獲取一個具有一些公共對象的commmon ModelAndView對象。實例化@postconstruct內部的@autowired bean內部控制器,spring
所以我爲所有控制器創建了一個超類 - BaseController,並且我通過調用一個方法initCommonData啓動了BaseController的構造函數中的通用模型對象,該方法使用@Autowired bean CommonDataService,它不存在於對象的構建時間和返回null
,所以我應該做的是在構造函數中獲得@autowired依賴。
僅供參考 - 我使用這種常見的服務和常用數據來獲取一些商品數據,這些商品數據將用於網站頁眉和頁腳中的每個jsp。 因此,如果在不調用每種控制器方法中的通用服務的情況下做到這一點,可以在每個控制器中建議。 這裏是我的代碼 - BaseController
@Controller
public class BaseController {
@Autowired
private CommonDataService commonDataService;
protected ModelAndView model;
public BaseController() {
this.initCommonData();
}
public void initCommonData(){
this.model = new ModelAndView();
this.model.addObject("headerData",commonDataService.getHeaderData());
this.model.addObject("footerData",commonDataService.getFooterData());
}
子控制器 -
@Controller
public class HomeController extends BaseController {
@Autowired
CategoryService categoryService;
@Autowired
CompanyService companyService;
@RequestMapping(value = { "", "/", "home" })
public ModelAndView homePage() {
model.setViewName("home");
.
.
.
model.addObject("name", value);
model.addObject("name2", value2);
return model;
}
CommonServiceClass -
@Service
public class CommonDataService {
@Autowired
CompanyService companyService;
@Autowired
CategoryService categoryService;
@Cacheable
public List<Category> getHeaderData(){
return categoryService.getTopCategoryList();
}
@Cacheable
public List<Company> getFooterData(){
return companyService.getTopCompanyList();
}
請建議,如果有這樣做的任何其他的好辦法,讓普通的數據從服務器到jsp。
你提到'@ PostConstruct'在您的標題,這是一個答案,你的麻煩,那麼你爲什麼不使用它? – Andreas
我試着@PostConstruct的解決方案,但它沒有被調用.. 發現了一些循環依賴問題,(做一些谷歌搜索後) –
使用postgui建議由javaguy,現在工作正常.. 不知道我在做什麼當我在接受的答案中使用javaguy的建議使用postconstruct時發生錯誤,並且postconstruct沒有被調用,, –