Casey Harrils
Casey Harrils

Reputation: 2963

hibernate/jpa Autowire annotation producing Nullpointer exception errors

New to java over here.

I am using Spring Boot and working with Eclipse Kepler to make a program.

Is it possible to define Autowired in regular class - or - MUST you use it ONLY in a Controller class?

I am trying to make a group of functions/methods in a class (ValFuncsAuth). With one of the methods (validateAuthInfo), I am getting the error:

java.lang.NullPointerException

listed below.

I created the "helper" function because - in different controllers - I was executing the same code. It is a kind of check/validation. I was trying to put it (the check/validation code) in one place (like a function). I wanted to make a call to this particular function for the check/validation (and not repeating the same code for each controller).

Why am I getting this error? Is there a way to fix this?

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)

I defined the following "helper" class

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 ...]
}

the 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 ...]

Upvotes: 1

Views: 147

Answers (1)

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

The problem with the way you are initializing your bean

ValFuncsAuth valfuncs = new ValFuncsAuth();

When you initialize your bean like this the spring container will not know about the autowired beans, you need to let the spring container initialize your object ( mark it as bean) so annotate your class with component

 @Component
 public class ValFuncsAuth {

and autowired it to your controller

@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 {

Now if you want your bean to use different object on each call of your api then you will just need to change the scope of your bean to prototype

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

Upvotes: 3

Related Questions