Reputation: 610
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();
}
}
Upvotes: 0
Views: 2403
Reputation: 1
use below annotations is the spring boot main method then it will solve the issue @EnableJpaRepositories("com.tech.repository") @EntityScan("com.tech.dto")
Upvotes: 0
Reputation: 6216
A few things to check :
Remove the static keyword from ConfigRepository
use it like :
@Autowired private ConfigRepository configRepository;
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")
.
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;
Upvotes: 1
Reputation: 140
Try adding, into PriceHandlerServiceApplication
class
@EnableJpaRepositories("repository.package")
also remove the static keyword
private static ConfigRepository configRepository;
Upvotes: 0