Java多线程中使用@Service注入的类和实例里面的方法

今天在使用多线程时,要在线程里面更新数据库中的某条是数据,然后使用注入的service层的实例,发现报了空指针异常,所以无法正常使用@Resource注解注入的实例,然后使用SpringUtils来获取注入的实例

工具类代码如下:

package com.umbrella.ubrlcloud.module.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * SpringUtils工具类获取bean
 * @since JDK 1.8
 */
@Component
public class SpringUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public static <T> T getBean(Class<T> tClass) {
		return applicationContext.getBean(tClass);
	}

	public static <T> T getBean(String name, Class<T> type) {
		return applicationContext.getBean(name, type);
	}

	public static HttpServletRequest getCurrentReq() {
		ServletRequestAttributes requestAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (requestAttrs == null) {
			return null;
		}
		return requestAttrs.getRequest();
	}

	public static String getMessage(String code, Object... args) {
		LocaleResolver localeResolver = getBean(LocaleResolver.class);
		Locale locale = localeResolver.resolveLocale(getCurrentReq());
		return applicationContext.getMessage(code, args, locale);
	}

}

该工具类是实现了ApplicationContextAware这个接口,通过里面的getBean方法来获取实例对象

使用代码如下:

InspectTaskDetailMapper inspectTaskDetailMapper = SpringUtils.getBean(InspectTaskDetailMapper.class);

这样就可以避免在多线程中去使用注入的实例报空指针异常的问题

猜你喜欢

转载自blog.csdn.net/Jackbillzsc/article/details/128081375
今日推荐