版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a913858/article/details/82807272
我们做项目过程中,有时候在一些工具类中难免会操作数据库。我们知道用原生态的sql,可以去实现,但是代码量太多还繁杂,如果可以引用一些封装的类去处理会更好。调用我们的类,需要引入进来。那么问题来了?怎么引入呢
因为工具类大多数都是static,用平常的注入方式不好使,就需要特定的方式来处理。开始上代码
首先我们创建一个获取bean的类,实现ApplicationContextAware 接口
package com.bonatone.common.mail.service.impl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
使用我们的getBean方法就能获取到我们想要的调用的bean。
获取到以后就可以去进行我们的操作。
在你需要的工具类中引入
DefaultService service = (DefaultService)SpringContextUtil.getBean("defaultService");