0

When i was testing my code in a single class "DeploiementController", it was running good. But now, i have splitted the code in 2 classes. But i'm facing a problem.. My IDE want that i put my variable has "private static", so i did it. I know that CategorieNamespace catnamespace = categorienamespacerepository.findBynamespacename(namespacename); can be null, it's normal, and it's why i test it just after.

But the problem is that now it crash ! with a null pointer exception..

My DeploiementController class :

package com.ent.intra.devops.endpoint;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ent.intra.devops.errors.NotFoundException;

import com.ent.intra.devops.getterclasses.DeploiementObject;
import com.ent.intra.devops.infrastructure.historydeployment.GenerateNewDeploymentHistory;

@RestController
public class DeploiementController {
    //ajouter un element dans historique de deploiement
    @PostMapping(value = "/addhistorydeployment")
    public String AddHistoriqueDeployment(@RequestBody DeploiementObject deploiementrecu) {
            if(deploiementrecu == null) {
                throw new NotFoundException("L'objet reçu est vide...");
            }else {
                String Resultat = GenerateNewDeploymentHistory.AddHistoriqueDeploymentMethod(deploiementrecu);
                return Resultat;
            }
    }
}

The GenerateNewDeploiementHistory class :

package com.ent.intra.devops.infrastructure.historydeployment;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.ent.intra.devops.accessingdatamysql.CategorieNamespaceRepository;
import com.ent.intra.devops.accessingdatamysql.HistoriqueDeploiementRepository;
import com.ent.intra.devops.accessingdatamysql.ServiceNamespaceRepository;
import com.ent.intra.devops.errors.NotFoundException;
import com.ent.intra.devops.getterclasses.CategorieNamespace;
import com.ent.intra.devops.getterclasses.DeploiementObject;
import com.ent.intra.devops.getterclasses.HistoriqueDeploiementObjectInsertion;
import com.ent.intra.devops.getterclasses.ServicesNamespace;

public class GenerateNewDeploymentHistory {

    @Autowired
    private static HistoriqueDeploiementRepository historiquedeploiementrepository;

    @Autowired
    private static CategorieNamespaceRepository categorienamespacerepository;

    @Autowired
    private static ServiceNamespaceRepository servicenamespacerepository;

    public static String AddHistoriqueDeploymentMethod(DeploiementObject deploiementrecu) {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = new Date();     
        Integer IdNamespace = 0;
        Integer IdService = 0;      
        String namespacename = deploiementrecu.getNamespace();
        String servicename = deploiementrecu.getService();
        String dateajout = dateFormat.format(date);
        System.out.println(namespacename);



        // Problem appears here "CategorieNamespace catnamespace...."
//      2020-04-15 11:21:26.743 ERROR 14868 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    
//      : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
//      [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException: null

        CategorieNamespace catnamespace = categorienamespacerepository.findBynamespacename(namespacename);
        ServicesNamespace servnamespace = servicenamespacerepository.findByservicename(servicename);


        try { 
            if(catnamespace != null) {                      
                IdNamespace = catnamespace.getId();
                System.out.println("id namespace : " +IdNamespace);
            }else {
                CategorieNamespace NewNameSpace = new CategorieNamespace();
                NewNameSpace.setNamespacename(namespacename);
                NewNameSpace.setDateajout(dateajout);
                categorienamespacerepository.save(NewNameSpace);
                IdNamespace = NewNameSpace.getId();
                System.out.println("L'ID Namespace vient d'être crée : "+ IdNamespace);
            }
        }catch (Exception ex) {
            throw new NotFoundException("La recherche du Namespace a échoué.");
        }


        try { 
            if(servnamespace != null) {                     
                IdService = servnamespace.getId();
                System.out.println("id Service : " +IdService);
            }else {
                ServicesNamespace NewService = new ServicesNamespace();
                NewService.setServicename(servicename);
                NewService.setDateajout(dateajout);
                servicenamespacerepository.save(NewService);
                IdService = NewService.getId();
                System.out.println("L'ID Service vient d'être crée : "+ IdService);
            }           
        }catch (Exception ex) {
            throw new NotFoundException("La recherche du Service a échoué.");
        }

        HistoriqueDeploiementObjectInsertion NewHistorique = new HistoriqueDeploiementObjectInsertion();
        NewHistorique.setIdnamespace(IdNamespace);
        NewHistorique.setIdservicenamespace(IdService);
        NewHistorique.setTagversion(deploiementrecu.getTagversion());
        NewHistorique.setDatedeploiement(deploiementrecu.getDatedeploiement());
        NewHistorique.setDatecreationtag(deploiementrecu.getDatecreationtag());
        NewHistorique.setActionby(deploiementrecu.getActionby());
        NewHistorique.setDateajout(dateajout);
        historiquedeploiementrepository.save(NewHistorique);
        return dateajout;



    }

}

I hope to understand what's wrong :)

3 Answers 3

1

Spring logic of inject instances is totally against the static logic.

Just delete all the static references

package com.ent.intra.devops.endpoint;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ent.intra.devops.errors.NotFoundException;

import com.ent.intra.devops.getterclasses.DeploiementObject;
import com.ent.intra.devops.infrastructure.historydeployment.GenerateNewDeploymentHistory;

@RestController
public class DeploiementController {

   @Autowired     // here you are injecting an instance
   GenerateNewDeploymentHistory generateNewDeploymentHistory;

    //ajouter un element dans historique de deploiement
    @PostMapping(value = "/addhistorydeployment")
    public String AddHistoriqueDeployment(@RequestBody DeploiementObject deploiementrecu) {
            if(deploiementrecu == null) {
                throw new NotFoundException("L'objet reçu est vide...");
            }else {
                String Resultat = generateNewDeploymentHistory.AddHistoriqueDeploymentMethod(deploiementrecu);
                return Resultat;
            }
    }
}

And the other class:

@Component // Here you declare that spring should create an instance
public class GenerateNewDeploymentHistory {

    @Autowired // no static
    private HistoriqueDeploiementRepository historiquedeploiementrepository;

    @Autowired
    private CategorieNamespaceRepository categorienamespacerepository;

    @Autowired
    private ServiceNamespaceRepository servicenamespacerepository;

    // neither static
    public String AddHistoriqueDeploymentMethod(DeploiementObject deploiementrecu) {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = new Date();     

Integer IdNamespace = 0;

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much ! Now it's ok in my head, no static :) as i was doing before.. but the ide say me to put it static.. so i did it.. Thanks again :)
0

Spring framework wires components into bean which are registered into the container, but even if you put a "@Component annotation" on GenerateNewDeploymentHistory then Spring cannot autowire and inject values in static fields. You need to wire them by your own.

1 Comment

Thanks for the help, but the help of @lucbel is very good. I'm not a pro and a full explanation is really helpful.
0

You are missing @Component annotation on GenerateNewDeploymentHistory. Note that autowiring works only on components. Moreover, since these components are created at runtime, static fields cannot be autowired. A way to autowire a static field would be to create a non static setter for the field and use @Autowired annotation on the setter. In this way, the field would be autowired, but at the runtime.

1 Comment

Thanks for the help, but it was my first time doing that. Thanks for the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.