溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

@Autowired 注入對(duì)自己new的對(duì)象無效,相當(dāng)于對(duì)象沒用spring管理

發(fā)布時(shí)間:2020-08-19 21:49:59 來源:網(wǎng)絡(luò) 閱讀:1372 作者:study_IT 欄目:編程語(yǔ)言

定義了一個(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是用注入方式定義的也不管用。

向AI問一下細(xì)節(jié)

免責(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)容。

AI