英文:
@Autowired fields are getting null when @PostConstruct method is called
问题
在ServiceB中,我的@Autowired字段为空
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceA {
@Autowired
private ServiceB serviceB
@PostConstruct
public void init() {
// 调用serviceB中的方法
serviceB.getService();
}
}
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceB {
@Autowired
private ServiceC serviceC // 为空
@Autowired
private ServiceD serviceD // 为空
@Autowired
private ServiceE serviceE // 为空
// 此方法从PostConstruct中调用
getService() {
serviceC.getAnotherService(); // 这里会得到NPE,因为serviceC为空
}
}
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceC {
getAnotherService() {
// 此方法未被调用
}
}
有没有办法在@PostConstruct之前加载所有@Autowired组件呢?
英文:
As stated in question in ServiceB my @Autowired
fields are getting null
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceA {
@Autowired
private ServiceB serviceB
@PostConstruct
public void init() {
// Calling method in serviceB
serviceB.getService();
}
}
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceB {
@Autowired
private ServiceC serviceC // Getting null
@Autowired
private ServiceD serviceD // Getting null
@Autowired
private ServiceE serviceE // Getting null
// This method is called from the PostConstruct
getService() {
serviceC.getAnotherService(); // Here getting NPE as serviceC is getting null
}
}
@Service
@Component
@ComponentScan({ "com.package" })
@Transactional
public class ServiceC {
getAnotherService() {
// This method is being not called
}
}
Is there any way to load all the @Autowired
components before @PostConstruct
专注分享java语言的经验与见解,让所有开发者获益!
评论