在非controller中直接使用自动装配,调用该service时会报空指针异常
@Component
@Data
public class BeautyMakeUpRequest {
@Autowired
private BeautyMakeUpService service;
}
因为BeautyMakeUpRequest初始化时并没有加载该service,所以需要用到@PostConstruct注解来实现初始化
@Component
@Data
public class BeautyMakeUpRequest {
@Autowired
private BeautyMakeUpService service;
static BeautyMakeUpRequest bean;
@PostConstruct
public void init(){
bean = this;
bean.service = service;
}
bean.service.function(.....);
}
调用service里的方法时,需要用已经加载过的bean来调用service。
@PostConstruct注解是javax.annotation的而非spring,PostConstruct影响了servlet的生命周期,在类的构造方法之后、servlet的init()之前执行