在Controller中直接使用service可行,而封装成工具类后调用出错,原因在于不能采用new方式加载service,必须将service的加载过程在服务器运行时进行。
这是我当时遇到的问题和最后的解决结论:http://bbs.csdn.net/topics/392162820
这是当时提问的时候有人提供的解决方案文章地址:http://blog.csdn.net/p793049488/article/details/37819121
解决静态工具类中使用注解注入service的重点在于两点:
1、在工具类中声明一个该工具类的静态的内部对象
2、使用注解@PostConstruct把需要使用的service加载到上面定义的静态内部对象中
例如下面的代码,重点就是29—37行代码:
1 package com.shanshan.bo.utils; 2 3 import java.util.List; 4 5 import javax.annotation.PostConstruct; 6 import javax.annotation.Resource; 7 8 import org.springframework.stereotype.Component; 9 10 import com.shanshan.bo.pojo.SsFundDimBank; 11 import com.shanshan.bo.pojo.SsFundDimCurrencyType; 12 import com.shanshan.bo.pojo.SsbiUser; 13 import com.shanshan.bo.service.SsFundDimBankService; 14 import com.shanshan.bo.service.SsFundDimCurrencyTypeService; 15 import com.shanshan.bo.service.SsbiUserService; 16 17 @Component 18 public class DataFactoryUtil { 19 20 @Resource 21 private SsbiUserService userService; 22 23 @Resource 24 private SsFundDimBankService bankService; 25 26 @Resource 27 private SsFundDimCurrencyTypeService currencyTypeService; 28 29 private static DataFactoryUtil dataFactoryUtil; 30 31 @PostConstruct 32 public void init() { 33 dataFactoryUtil = this; 34 dataFactoryUtil.userService = this.userService; 35 dataFactoryUtil.bankService = this.bankService; 36 dataFactoryUtil.currencyTypeService = this.currencyTypeService; 37 } 38 39 /** 40 * 根据用户名去数据库查询用户并返回 41 * Ps:暂不考虑用户名重复的问题 42 * @param username 43 * @return User 44 */ 45 public static SsbiUser selectByUsername(String username) { 46 if (username != null && !("".equals(username))) { 47 return dataFactoryUtil.userService.selectByUserCode(username); 48 } 49 return null; 50 } 51 52 /** 53 * 查询所有的银行数据并返回 54 */ 55 public static List<SsFundDimBank> selectAllBank() { 56 return dataFactoryUtil.bankService.selectAll(); 57 } 58 59 /** 60 * 查询所有的币制数据并返回 61 */ 62 public static List<SsFundDimCurrencyType> selectAllCurrencyType() { 63 return dataFactoryUtil.currencyTypeService.selectAll(); 64 } 65 }