静态工具类中使用@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);
}
}
以上是 静态工具类中使用@Autowired的方法 的全部内容, 来源链接: utcz.com/z/512692.html