标签:ppi 情况 body request 修改 一个 ring result ltm
定义了一个接口实现类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是用注入方式定义的也不管用。
@Autowired 注入对自己new的对象无效,相当于对象没用spring管理
标签:ppi 情况 body request 修改 一个 ring result ltm
原文地址:https://blog.51cto.com/9784292/2429540