@Autowired inject their own new objects is invalid, the equivalent of useless objects spring management

Defines an interface UserServiceImpl class, and the class with the control UserService userService = new UserServiceImpl (); implementation class to create the object, call the class method implementation userService.queryById (id), it will be reported to a null pointer, when executed sentence jpaQueryFactory error.

Code is as follows
implementation class:
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;
}

}

Solution: modifying the control class, the class definitions implemented by way of injection, the following
@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;
}

}

The reason Description: This is not because of his new object is caused to spring management, this situation is equivalent to useless spring management, so it will not be automatic dependency injection, jpaQueryFactory nature is null, when used on an empty report pointer exception, though jpaQueryFactory is defined with the injection method does not work.

Guess you like

Origin blog.51cto.com/9784292/2429540