@Autowired字段在调用@PostConstruct方法时变为null

huangapple 未分类评论55阅读模式
英文:

@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

huangapple
  • 本文由 发表于 2020年5月4日 18:33:36
  • 转载请务必保留本文链接:https://java.coder-hub.com/61590188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定