十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
定義了一個接口實現(xiàn)類UserServiceImpl,并在控制類中用UserService userService=new UserServiceImpl(); 創(chuàng)建實現(xiàn)類的對象,調(diào)用實現(xiàn)類的方法userService.queryById(id),執(zhí)行到j(luò)paQueryFactory這句時會報空指針錯誤。

創(chuàng)新互聯(lián)建站成都企業(yè)網(wǎng)站建設(shè)服務(wù),提供成都網(wǎng)站建設(shè)、做網(wǎng)站網(wǎng)站開發(fā),網(wǎng)站定制,建網(wǎng)站,網(wǎng)站搭建,網(wǎng)站設(shè)計,響應(yīng)式網(wǎng)站,網(wǎng)頁設(shè)計師打造企業(yè)風(fēng)格網(wǎng)站,提供周到的售前咨詢和貼心的售后服務(wù)。歡迎咨詢做網(wǎng)站需要多少錢:18980820575
代碼如下
實現(xiàn)類:
import ...
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
JPAQueryFactory jpaQueryFactory;
@Override
public List
List
QUserEntity qUserEntity=QUserEntity.userEntity;
Predicate predicate1=qUserEntity.id.eq(id).and(qUserEntity.state.eq("10A"));
list=jpaQueryFactory.selectFrom(qUserEntity)
.where(predicate1)
.fetch();
return list;};
}
控制類:
import ...
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("api/user/")
public class UserController {
@ResponseBody
@RequestMapping(value = "getTree" , method = RequestMethod.POST)
public Map getTree(@RequestBody UserTreeDto dto){
UserService userService=new UserServiceImpl();
List list = userService.queryById(id);
resultMap.put("data",list);
resultMap.put("result","suc");
return resultMap;
} }
解決辦法:修改控制類,用注入的方式定義實現(xiàn)類,如下
@Controller
@RequestMapping("api/user/")
public class UserController {
@Autowired
UserService userService;
@ResponseBody
@RequestMapping(value = "getTree" , method = RequestMethod.POST)
public Map getTree(@RequestBody UserTreeDto dto){
Interger id=dto.getId();
List list = userService.queryById(id);
resultMap.put("data",list);
resultMap.put("result","suc");
return resultMap;
} }
原因說明:這是因為自己new的對象沒被spring管理導(dǎo)致的,這種情況就相當(dāng)于沒用spring管理,所以它不會自動進(jìn)行依賴注入,jpaQueryFactory自然就是null,當(dāng)用到的時候就報空指針異常了,盡管jpaQueryFactory是用注入方式定義的也不管用。