一般来说,注入的 bean的方式为使用注解,但有时候,是不方便使用注解注入bean,就用到了下面的工具类,使用方式:
IPersonRequestLogService iPersonRequestLogService = SpringUtil.getBean(IPersonRequestLogService.class);
工具类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
/**
* spring 工具类
*
* @author Admin
*/
@Slf4j
@Component("springUtil")
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringUtil.context = context;
}
public static <T> T getBean(Class<T> clazz) {
if (clazz == null) {
return null;
}
return context.getBean(clazz);
}
public static <T> T getBean(String beanId) {
if (beanId == null) {
return null;
}
return (T) context.getBean(beanId);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
if (null == beanName || "".equals(beanName.trim())) {
return null;
}
if (clazz == null) {
return null;
}
return (T) context.getBean(beanName, clazz);
}
public static ApplicationContext getContext() {
if (context == null) {
return null;
}
return context;
}
public static void publishEvent(ApplicationEvent event) {
if (context == null) {
return;
}
try {
context.publishEvent(event);
} catch (Exception ex) {
log.error(ex.getMessage());
}
}
}