首页 > 其他分享 >调用工具类方法的注意事项

调用工具类方法的注意事项

时间:2022-11-14 16:25:06浏览次数:41  
标签:调用 private ConvertUtils 注意事项 convertUtils 工具 方法

当我们调用一个工具类的方法的时候 eg:

工具类:

@Component
public class ConvertUtils {
   @Resource
private JcdeptMapper jcdeptMapper;

@Autowired
private JcdeptController jcdeptController;

@Autowired
private JcdeptDao jcdeptDao;


  //方法一:
   public List<String> findName(String DEPTCODE) {
  .........
}
}

当我们调用该工具类的方法一:findName()方法时,引用该工具类时,容易出现问题。
eg:
ConvertUtils convertUtils = new ConvertUtils();
这样写的话会报 Dao 或 Mapper 为空的错:
也就是没有成功引入该工具类,调不到该工具类中的方法。

原因:
使用 new 工具类的方式调用工具类中的方法是错误的,因为
ConvertUtils convertUtils = new ConvertUtils();

是调用了无参构造方法创建对象:convertUtils,该对象没有
任何属性和方法,此时在ConvertUtils工具类中也没有给他加上
get() set() 方法去设置属性等。
而ConvertUtils工具类已经使用@Component注解将该工具类
注入到容器中交给spring去管理了,我们想到用该工具类中的方法
的话,只需要将该工具类注入到我们想要调用该工具类方法的代码中
就行了
eg:
@Service
public class EnergyServiceIml extends ServiceImpl<EnergyMapper, EnergyDailyStatistics> implements EnergyService {

@Autowired
private ConvertUtils convertUtils;

此时我们就可以使用convertUtils 对象 去调用该实体类中的方法了。



 

标签:调用,private,ConvertUtils,注意事项,convertUtils,工具,方法
From: https://www.cnblogs.com/sensenh/p/16889191.html

相关文章