java工具类静态方法和单例_静态工具类中使用@Autowired的方法

静态工具类中使用@Autowired的方法

在Spring项目中我习惯使用@Autowired来注入Service层或者Dao层,在一次偶然我在静态方法中查询数据库数据,而报了NullPointerException,一路找来发现Mapper为Null,分析原因发现Spring不支持依赖注入static静态变量,静态变量/类变量不是对象的属性而是一个类的属性,spring则是基于对象层面上的依赖注入,好了不罗嗦了,下面给出解决方案直接上代码。

静态工具类:

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**

* @Author: Wenx

* @Description: 静态工具类中使用@Autowired的方法

* @Date: Created in 2020/1/13 20:29

* @Modified By:

*/

@Component

public class DaoUtils {

private static final Logger logger = LoggerFactory.getLogger(DaoUtils.class);

private static DaoUtils utils;

@Autowired

private TestMapper testMapper;

@PostConstruct

public void init() {

utils = this;

}

public static TestDO getTest(Integer id) {

TestDO testDO = utils.testMapper.selectTestById(1);

return testDO;

}

}

Mapper:

import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

import org.springframework.stereotype.Repository;

/**

* @Author: Wenx

* @Description:

* @Date: Created in 2020/1/13 20:32

* @Modified By:

*/

@Mapper

@Repository

public interface TestMapper {

/**

* 查询table_test表记录

*

* @param id ID

* @return TestDO

*/

@Select("select id,name from table_test where id = #{id}")

TestDO selectTestById(@Param("id") Integer id);

}

实体:

/**

* @Author: Wenx

* @Description:

* @Date: Created in 2020/1/13 20:35

* @Modified By:

*/

public class TestDO {

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

启动类:

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.ApplicationContext;

/**

* @Author: Wenx

* @Description: 启动类

* @Date: Created in 2020/1/13 20:13

* @Modified By:

*/

@SpringBootApplication

public class StudyDemoApplication {

private static final Logger logger = LoggerFactory.getLogger(StudyDemoApplication.class);

public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(StudyDemoApplication.class, args);

TestDO testDO = DaoUtils.getTest(1);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值