我有一个使用 Spring 3 的 JPA 应用程序。我正在尝试使用 @PostConstuct 来初始化具有特定设施代码的数据库。当我在具有 @PostConstuct 方法的类中保留代码时 - 它可以工作。当我调用第二个类来保存代码时,它失败了。这与我使用 @Autowired 注释的方式有关吗?
这是 Preloader 类的一部分:
public class Preloader {
@Autowired
private FacilityService service;
@PostConstruct
public void init() {
loadCodeSet();
}
private void loadCodeSet() {
// This works
Facility created = new Facility();
created.setCode("Uni");
created.setDescription("University");
Facility returned = service.create(created);
// This fails
CodeSetLoader cl = new CodeSetLoader();
l.load();
}
这是加载类的一部分:
public class CodeSetLoader {
@Autowired
private FacilityService facilityService;
public void load() {
loadFacilities();
}
private void loadFacilities() {
Facility test = new Facility();
test.setCode("UNI");
test.setDescription("University");
Facility returned = facilityService.create(test);
}
例外情况包括:
Caused by: java.lang.NullPointerException
at util.CodeSetLoader.loadFacilities(CodeSetLoader.java:42)
at util.CodeSetLoader.load(CodeSetLoader.java:24)
at util.Preloader.loadCodeSet(Preloader.java:68)
at util.Preloader.init(Preloader.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130)
... 22 more
希望有人可以提供帮助吗?