@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 {
@AutowiredUserService 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是用注入方式定义的也不管用。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。