Reputation: 107
I have a controller class which is below. I have a TagRepository
interface which extends JPA repository which I am using to save TagReader
instance to my DB and it works fine when I use it in my controller class. However, when I try to use tagRepository
in another class and try to save my TagReader
object from there it throws a null pointer exception.
The following logic works fine.
@RestController
public class Controller {
@Autowired
TagRepository tagRepository;
@Autowired
Rfid6204Connection rfid6204Connection;
@RequestMapping(value = "/test")
public void testRepoController(){
String tagid = "0x3504ACE6E0040E5147D516A6";
String serial ="00333478";
String departure ="2017-12-22T12:16:58.857";
String type = "ISOC";
TagReader tagReader = new TagReader(tagid,serial,departure,type,"5");
tagRepository.save(tagReader);
}
}
The following logic throws a null pointer exception.
@component
public class Rfid6204Connection{
@Autowired
static TagRepository tagRepository;
public static void test(TagReader tag){
tagRepository.save(tag);
}
}
Can someone please tell me what the issue is?
Upvotes: 0
Views: 432
Reputation: 1059
you couldn't autowired static variables directly
then, you have some options. first, autowired instance of TagRepository and after dependency injection set a instance to static variable
@Component
public class Rfid6204Connection {
private static TagRepository sTagRepository;
@Autowired
private TagRepository tagRepository;
@PostConstruct
public void init() {
Rfid6204Connection.sTagRepository = tagRepository;
}
}
second prepare setter method of TagRepository and put a autowired
public class Rfid6204Connection {
private static TagRepository tagRepository;
@Autowired
public void setTagRepository(TagRepository tagRepository) {
Rfid6204Connection.tagRepository = tagRepository;
}
}
but originally ... you shoudn't autowire to static variables.
Upvotes: 1
Reputation: 7890
You made the Autowired field static and when the class loader loads the static values, the Spring context is not yet loaded and your object is not correctly initialized; remove the static keyword:
@Autowired
private TagRepository tagRepository;
Upvotes: 1
Reputation: 21903
I think you are using Rfid6204Connection.test
as a static method. Spring doesn't work with Static methods. It works with Objects instantiated by the Spring Container. So change your Rfid6204Connection
as below;
@Component
public class Rfid6204Connection{
@Autowired
private TagRepository tagRepository;
public void test(TagReader tag){
tagRepository.save(tag);
}
}
And use it wherever you want as below;
@Autowired
Rfid6204Connection rfid6204Connection;
// Within a method or constructor
rfid6204Connection.test(tag);
Upvotes: 2