普通类或Util类依赖注入@Service或@Mapper

2022-06-30 09:17:15

普通类或Util类依赖注入@Service或@Mapper

在测试代码时候发现一个接口报空值错误,经过debug测试,发现没有注入mapper,mapper在执行时候是空的,所以调用sqlde 时候报错

原因是如果我们要在自己封装的util工具类中或者非controller普通类中使用@Autowried注解注入Service或者Mapper接口,直接注入是不能的,因为util使用了静态的方法,我们是无法直接使用非静态接口的,(spring不能注入static变量的原因:
Spring依赖注入是依赖set方法
set方法是普通的对象方法
static变量是类的属性

注解方式:
时间上这个init()的方法是可以自己随便定义的


```java
 @Autowired
    private ClaimsPolicyMapper claimsPolicyMapper;会直接成null值。
    解决方案:
    将bean注入到spring容器中。
    
     @Component
	 public class CheckScoresUtil {
    private static Logger logger = LoggerFactory.getLogger(CheckScoresUtil.class);
    @Autowired
    private ClaimsPolicyMapper claimsPolicyMapper;

    private static CheckScoresUtil checkScoresUtil;

    @PostConstruct
    public void init() {
        checkScoresUtil = this;
        checkScoresUtil.claimsPolicyMapper = this.claimsPolicyMapper ; // 初使化时将已静态化的testService实例化
    }
}

2 xml配置

我们可以把init()方法上的@PostConstruct注解去掉,在spring-comtext.xml中配置以下bean就好了,

<bean id="testUtils" class="这里写utils类的包全路径名" init-method="init"></bean>


实现InitializingBean, DisposableBean这两个接口,并复写afterPropertiesSet()和destroy()方法

示例代码如下:

```java
public class InitializingDisposableInit implements InitializingBean,
        DisposableBean {

    @Override
    public void destroy() throws Exception {
        System.out.println("执行InitializingDisposableInit: destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("执行InitializingDisposableInit: afterPropertiesSet");
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:beans-impl.xml");
        context.close();
    }
}

本文转载自:https://blog.csdn.net/wqc19920906/article/details/80009929

  • 作者:qq_49382338
  • 原文链接:https://blog.csdn.net/qq_49382338/article/details/116779207
    更新时间:2022-06-30 09:17:15