Reputation: 25
I've autowired a JPA repository that adds dummy data in my H2 database before the application starts. But is there a reason as to why I can't use it in the main () method but am able to use it in the runner() method?
@SpringBootApplication
public class FullstackApplication {
@Autowired
private CarRepository carRepository;
private static final Logger logger = LoggerFactory.getLogger(FullstackApplication.class);
public static void main(String[] args) {
carRepository. // Here I get a compilation error: Cannot make a static reference to a non-static field
SpringApplication.run(FullstackApplication.class, args);
}
@Bean
CommandLineRunner runner(){
return args -> {
// Save demo data to database
carRepository.save(new Car("Ford", "Mustang", "Red",
"ADF-1121", 2017, 59000));
carRepository.save(new Car("Nissan", "Leaf", "White",
"SSJ-3002", 2014, 29000));
carRepository.save(new Car("Toyota", "Prius", "Silver",
"KKO-0212", 2018, 39000));
};
}
}
Upvotes: 1
Views: 2323
Reputation: 140
Well main method is marked as static and you cannot access non static members from a static method.
To just solve that you have to mark the carRepository static. But since static field cannot be autowired it will ignore it and you will not get the object.
It will work in command runner because at that time the sprint start up is already finished and beans has been instantiated.
Upvotes: 1
Reputation: 551
Main method is marked static, which means, everything that is used there should be either static as well , or be manually instantiated.
You do not instantiate CarRepository manually in static body of main method, you are relying on Spring to instantiate it somewhere during its startup phase , which will happen after "carRepository. //...." this line.
That is why , you cannot use carRepository in this exact place, because it is not static by itself and in was not manually instantiated.
In CommandRunner though , at the time return is being called , instance of CarRepository is already created by Spring and autowired to field, because Spring startup already has finished , and it can be easily used.
Upvotes: 2
Reputation: 1
You are accessing a non static field directly from static method which is not permitted in java
Also you cannot make static field @Autowired
so if you do this
@Autowired
private static CarRepository carRepository;
it won't throw any error but it will be ignored.
Upvotes: 2