需求
项目中需要在一个utils工具类中,调用mapper对象进行查询并进行排序后选出数值最小的数值,然而静态方法里面直接注入会报空指针的错误。现在总结一下解决办法。
重要点
1、若要进行排序,需要重写该实体类的compareTo()方法,实现Comparable接口。代码如下
@Override
public int compareTo(Object o) {
if(o instanceof TbHotelMenu){
TbHotelMenu menu=(TbHotelMenu) o;
int oP = (int) Double.parseDouble(menu.getMenuPrice());
int tP = (int) Double.parseDouble(this.getMenuPrice());
return tP-oP;//升序
//return tP-oP;//降序
}
return 0;
}
2、需要将该工具类注入到spring 。applicationContext-service.xml配置文件代码如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
">
<!-- 扫描包加载Service实现类 -->
<context:component-scan base-package="com.test.server.service"></context:component-scan>
<context:component-scan base-package="com.test.server.util"></context:component-scan>
3、
a、utils类上面添加@Component注解
b、@Autowired注入需要使用的mapper对象,注意不是静态的
c、创建一个静态的这个utils的对象
d、创建一个init方法,添加@PostConstruct注解,代码内容如下
@Component
public class LowestMenuPrice {
@Autowired
private TbHotelMenuMapper menuMapper;
private static LowestMenuPrice menuPrince;
@PostConstruct
public void init(){
menuPrince = this;
menuPrince.menuMapper = this.menuMapper;
}
//获取酒楼菜单价钱最低的菜单价格
public static String getLowestPrince(long hotelId){
TbHotelMenuExample example=new TbHotelMenuExample();
TbHotelMenuExample.Criteria criteria = example.createCriteria();
criteria.andHotelIdEqualTo(hotelId);
List<TbHotelMenu> menuList = menuPrince.menuMapper.selectByExample(example);
if(menuList!=null&&menuList.size()>0){
Collections.sort(menuList);
String menuPrice = menuList.get(0).getMenuPrice();
Double valueOf = Double.valueOf(menuPrice);
DecimalFormat Format=new DecimalFormat("#.00");
String price=Format.format(valueOf);
return price;
}
return "0.00";
}
}