SpringBoot小结:componentScan自定义类注入问题
一般注入,使用@Autowired就好了,把service自动装配进来,但有的时候,我们自定义工具类,例如Util,需要调用。有两种方式
- 自动装配 @Autowired
@Autowired
private SimulateShipUtil simulateShipUtil; - new进来。
@PostConstruct的方法,把自己静态实例化,需要设置成静态static,
/**
* 让其他类能够调用mapper和service的方法
* https://blog.youkuaiyun.com/qq_21454973/article/details/89446823
*/
@Component
public class MapperUtil {
@Autowired
private ShipUploadMapper shipUploadMapper;
public static MapperUtil mapperUtil;
@PostConstruct
public void init(){
mapperUtil = this;
mapperUtil.shipUploadMapper = this.shipUploadMapper;
}
public static String getShipUploadCDID(Integer MMSI){
return mapperUtil.shipUploadMapper.getChannelDivisionID(MMSI);
}
}