Search code examples
javaspringspring-boothibernatejpa

JpaRepository getting Null at service class


I'm new for Java Spring boot and I'm developing REST API by using JPA. So, I want to access JpaRepository outside the @RestController. And I use @Component annotation top of the class header and use @Autowired annotation for declaring my repository instance. But, repository instance always getting null.


Application class

@SpringBootApplication
@EnableJpaAuditing
public class PriceHandlerServiceApplication
{
    public static void main( String[] args )
    {
        SpringApplication.run( PriceHandlerServiceApplication.class, args );
    }
}

Repository

@Repository
public interface ConfigRepository extends JpaRepository<ServiceConfiguration,Long>
{
}

Model Class

@Entity
@Table( name = "service_configuration" )
@EntityListeners( AuditingEntityListener.class )
public class ServiceConfiguration
{
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    @JsonProperty("id")
    private Long id;

    @NotBlank
    @JsonProperty( "name" )
    private String name;

    @JsonProperty( "value" )
    private Double value;

    public ServiceConfiguration()
    {}
 }

Service Class

@Component
public class ConfigurationHandler
{
    @Autowired
    private static ConfigRepository configRepository;
    
    public static List<ServiceConfiguration> getAllConfigurations(){
        return configRepository.findAll();
    }
}

And I call ConfigurationHandler.getAllConfigurations() by another class. But configRepository always getting null.

[UPDATED] Remove static keyword but still not working. still configRepository repository getting null

@Component
public class ConfigurationHandler
{
    @Autowired
    private ConfigRepository configRepository;

    public ConfigurationHandler()
    { }

    public List<ServiceConfiguration> getAllConfigurations()
    {
        return configRepository.findAll();
    }

}


Solution

  • A few things to check :

    1. Remove the static keyword from ConfigRepository use it like :

      @Autowired private ConfigRepository configRepository;

    2. Ensure that your repository interface and entity classes are under the main Application.java package or ensure that your Application.java is at the root of your package so that springboot auto configuration will automatically take up the repository , otherwise use the @EnableJpaRepositories(basePackages="your.package").

    3. Ensure that the component class that you are trying to auto-wire the repository is actually managed by spring when you are using it. That is DO NOT use the new keyword if you want autowiring to work in your component class. So, when you want to use ConfigurationHandler use it like :

      @Autowire private ConfigurationHandler configurationHandler;