如果我在控制器中向模型添加属性,则会多次调用内部函数
例如。我有这个代码:
IndexController.java:
@RequestMapping(value="/index")
public String index(Model model) {
//Select Advertisement
model.addAttribute("ad", advertisementHandler.getAdvertisement());
logger.debug("Hello");
return "index";
}
现在getAdvertisement()被多次调用,所以终端显示这个日志:
DEBUG [01-11-2015 05:16:17] foobar.model.advertisement.Advertisement - 观看广告ID:3
DEBUG [01-11-2015 05:16:17] foobar.controller.CustomerController - 你好 DEBUG [01-11-2015 05:16:18] foobar.model.advertisement.Advertisement - 观看广告ID:3
DEBUG [01-11-2015 05:16:18] foobar.model.advertisement.Advertisement - 已浏览广告ID:4
AdvertisementHandler.java:
public Advertisement getAdvertisement() {
List<Advertisement> ads = this.advertisementRepository.findValidAdvertisements();
if(ads == null || ads.size() == 0)
return null;
int rnd = new Random().nextInt();
rnd = rnd < 0 ? -1 * rnd : rnd;
Advertisement ad = ads.get(1 + (rnd % (ads.size() - 1)));
ad.viewed();
return this.advertisementRepository.save(ad);
}
Advertisement.java(Entity):
public void viewed() {
this.views++;
logger.debug("Viewed Advertisement with ID: " + String.valueOf(this.id));
}
有人知道如何解决它吗?