您好,登錄后才能下訂單哦!
定義了一個(gè)接口實(shí)現(xiàn)類UserServiceImpl,并在控制類中用UserService userService=new UserServiceImpl(); 創(chuàng)建實(shí)現(xiàn)類的對(duì)象,調(diào)用實(shí)現(xiàn)類的方法userService.queryById(id),執(zhí)行到j(luò)paQueryFactory這句時(shí)會(huì)報(bào)空指針錯(cuò)誤。
代碼如下
實(shí)現(xiàn)類:
import ...
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
JPAQueryFactory jpaQueryFactory;
@Override
public List<UserEntity> queryById(Interger id){
List<UserEntity> list=null;
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<String, Object> getTree(@RequestBody UserTreeDto dto){
UserService userService=new UserServiceImpl();
List<UserEntity> list = userService.queryById(id);
resultMap.put("data",list);
resultMap.put("result","suc");
return resultMap;
}
}
解決辦法:修改控制類,用注入的方式定義實(shí)現(xiàn)類,如下
@Controller
@RequestMapping("api/user/")
public class UserController {
@Autowired
UserService userService;
@ResponseBody
@RequestMapping(value = "getTree" , method = RequestMethod.POST)
public Map<String, Object> getTree(@RequestBody UserTreeDto dto){
Interger id=dto.getId();
List<UserEntity> list = userService.queryById(id);
resultMap.put("data",list);
resultMap.put("result","suc");
return resultMap;
}
}
原因說明:這是因?yàn)樽约簄ew的對(duì)象沒被spring管理導(dǎo)致的,這種情況就相當(dāng)于沒用spring管理,所以它不會(huì)自動(dòng)進(jìn)行依賴注入,jpaQueryFactory自然就是null,當(dāng)用到的時(shí)候就報(bào)空指針異常了,盡管jpaQueryFactory是用注入方式定義的也不管用。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。