hibernate / jpa Autowire注释产生Nullpointer异常错误

时间:2017-08-20 05:02:38

标签: java spring hibernate spring-data-jpa

这里的java新手。

我正在使用Spring Boot并与Eclipse Kepler一起制作程序。

是否可以在常规类中定义Autowired - 或 - 必须仅在Controller类中使用它?

我正在尝试在类中创建一组函数/方法(ValFuncsAuth)。使用其中一个方法(validateAuthInfo),我收到错误:

  

显示java.lang.NullPointerException

列在下面。

我创建了“帮助器”函数,因为 - 在不同的控制器中 - 我正在执行相同的代码。这是一种检查/验证。我试图将它(检查/验证代码)放在一个地方(就像一个函数)。我想调用这个特定函数进行检查/验证(而不是为每个控制器重复相同的代码)。

为什么我收到此错误?有办法解决这个问题吗?

TIA

java.lang.NullPointerException: null
    at ccinfw.helpfulfunctions.ValFuncsAuth.validateAuthInfo(ValFuncsAuth.java:121)
    at ccinfw.controller.work.WorkProjectController.createProject(WorkProjectController.java:97)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)

我定义了以下“帮助者”类

public class ValFuncsAuth {

    private static final Logger logger = LoggerFactory
            .getLogger(CustomerController.class);
    private SecureRandom random = new SecureRandom();

    [... snip ...]

    @Autowired
    private MstrstoreheadDAO companydao;

    [... snip ...]

    public void validateAuthInfo(BigDecimal tenantid,
            BigDecimal authid, String authtype, String timezone)
            throws Exception {

    [... snip ...]

        try {

            // get company info - make sure it exists
            companyitem = companydao.findByTenantid(tenantid);  <<<< --- GET THE ERROR HERE

            if (companyitem.size() != 1) {
                throw new DataInputException(
                        " => EMSG-25590 - invalid tenantid passed in : ->"
                                + tenantid);
            }
    [... snip ...]
}

DAO

@Transactional
@Repository
public interface MstrstoreheadDAO extends CrudRepository<Mstrstorehead, BigDecimal> {

    public List<Mstrstorehead> findAll();

    public List<Mstrstorehead> findByTenantid(BigDecimal id);
}

iniitaliztion

@RequestMapping(value = "/create/{tenantid}/{jobid}", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Void> createJob (
            @PathVariable BigDecimal tenantid,
            @PathVariable BigDecimal jobid,
            @RequestBody WorkJobChargesParamIOPOJO input) throws Exception {

        ValFuncsAuth valfuncs = new ValFuncsAuth();

        try {

    [... snip ...]
            /**
             * make sure the person who is creating the record (the WORKER) is
             * authorized to do so - convert his/her timezone as well
             */
            valfuncs.validateAuthInfo(tenantid, input.getLoggedinreclockid(),
                    input.getLoggedinreclocktype(), input.getLoggedintimezone());

    [... snip ...]

1 个答案:

答案 0 :(得分:3)

初始化bean的方式存在问题

ValFuncsAuth valfuncs = new ValFuncsAuth();

当您初始化bean时,spring容器将不知道自动装配的bean,您需要让spring容器初始化您的对象(将其标记为bean),以便使用组件注释您的类

 @Component
 public class ValFuncsAuth {

并将其自动连接到您的控制器

@Autowired
private ValFuncsAuth valFuncsAuth;

@RequestMapping(value = "/create/{tenantid}/{jobid}", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Void> createJob (
        @PathVariable BigDecimal tenantid,
        @PathVariable BigDecimal jobid,
        @RequestBody WorkJobChargesParamIOPOJO input) throws Exception {

现在,如果您希望bean在每次调用api时使用不同的对象,那么您只需要将bean的范围更改为原型

@Component
@Scope("prototype")
public class ValFuncsAuth {