在spring framework 4.0中,我有一个继承自GenericService的SpecificService,它是一个Injected with a service。 SpecificService无法访问Injected服务。
有没有办法让子类(SpecificService)可以访问Injected服务?
// GenericService.java
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class GenericService {
@Inject
OtherService otherService;
// ...
private void fn() {
System.out.println(otherService) // (id = 12)
}
}
// SpecificService.java
class SpecificService extends GenericService {
// ...
private void fn() {
System.out.println(otherService) // null
}
}
答案 0 :(得分:0)
// GenericService.java
public abstract class GenericService {
protected final OtherService otherService;
public GenericService (OtherService otherService) {
this.otherService = otherService;
}
// ...
private void fn() {
System.out.println(otherService) // (id = 12)
}
}
// SpecificService.java
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
class SpecificService extends GenericService {
@Inject
public SpecificService (OtherService otherService) {
super(otherService);
}
private void fn() {
System.out.println(otherService) // null
}
}
我不是100%这是有效的,因为我只使用了@Autowired的Spring 3,但是我遇到了同样的问题,这就是解决方案。假设您也可以在构造函数参数上使用@Inject。