@Autowired 注入对自己new的对象无效,相当于对象没用spring管理

定义了一个接口实现类UserServiceImpl,并在控制类中用UserService userService=new UserServiceImpl(); 创建实现类的对象,调用实现类的方法userService.queryById(id),执行到jpaQueryFactory这句时会报空指针错误。

代码如下
实现类:
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;
}

}

解决办法:修改控制类,用注入的方式定义实现类,如下
@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;
}

}

原因说明:这是因为自己new的对象没被spring管理导致的,这种情况就相当于没用spring管理,所以它不会自动进行依赖注入,jpaQueryFactory自然就是null,当用到的时候就报空指针异常了,尽管jpaQueryFactory是用注入方式定义的也不管用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值