加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

解决非controller使用@Autowired注解注入为null问题

(2017-06-01 18:49:58)
标签:

it

分类: springmvc

在SpringMVC框架中,我们经常要使用@Autowired注解注入Service或者Mapper接口,我们也知道,在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当我们遇到这样的问题,我们就要想办法解决了。

@Autowired注解的方法:


@Component
 public class TestUtils { 

 @Autowired 
 private ItemService itemService; 

 @Autowired 
 private ItemMapper itemMapper;

 public static TestUtils testUtils; 

 @PostConstruct 
 public void init() { 
  testUtils = this;
   

 //utils工具类中使用service和mapper接口的方法例子,用"testUtils.xxx.方法" 就可以了 
 public static void test(Item record){ 

  testUtils.itemMapper.insert(record); 
  testUtils.itemService.queryAll(); 

 } }
 
我们在init方法中使用以下注解就可以了,时间上这个init()的方法是可以自己随便定义的,注意:inti()方法里面不用写任何东西,跟我这样的就绝对ok了,不用看网上其他人瞎掰!


如果以上不能解决,只能直接用dao层:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
FcglEsHouseMapper sfMapper = context.getBean(FcglEsHouseMapper.class);

然后直接调mybatis接口,不推荐此种,违背springmvc

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有