maha.benjebara
maha.benjebara

Reputation: 242

NullPointerException on CrudRepository

I have created a repository but when I call my repository it gives a NullPointerException everytime. Can someone help me figure out why?

My repository

@Repository
public interface WorkflowObjectRepository extends CrudRepository<WorkflowObject, String> {

    @Override
    WorkflowObject findOne(String id);

    @Override
    void delete(WorkflowObject workflowObject);

    @Override
    void delete(String id);

    @Override
    WorkflowObject save(WorkflowObject workflowObject);

}

My Object

@Data
@Entity
@Table(name = "workflowobject")
public class WorkflowObject {

    @GeneratedValue
    @Column(name="id")
    private String id;

    @Column(name = "state_name")
    private String stateName;

}

My test

public class Test {

    @Autowired
    static WorkflowObjectRepository subject;

    public static void main(String[] args) {

        final WorkflowObject obj = new WorkflowObject();
        obj.setId("maha");
        obj.setStateName("test");
        subject.findOne("maha");
    }

}

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/vtr?
autoReconnect=true
spring.datasource.username=vtr
spring.datasource.password=vtr

Upvotes: 2

Views: 2774

Answers (2)

Zetared
Zetared

Reputation: 110

In order to work properly with @Autowired you need to keep in mind that spring scans annotations to allow automatically classes load.

If you need to @Autowired some class, the class Test needs to have some annotation, that tells to Spring Boot to find it.

Your Test class need to have @Component, @Service, @Controller, @Repository, etc. Otherwise @Autowired will not work because Spring Boot not know your class and will not process it.

You can find some explanation here

Upvotes: 0

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

The problem is you are trying to autowire a static data member

@Autowired
static WorkflowObjectRepository subject;

What happens in your case is static is getting initialized before the bean so you are autowiring on null, just remove the static and deal with it as instance variable.

repositories are singletones so no point of making them static

Upvotes: 3

Related Questions