解决@Autowired获取不到bean实例的解决办法
1.PublicSqlMapper sqlMapper = ApplicationContextUtils.getBean(PublicSqlMapper.class);
package com.admin.common.utils.bean;
import org.apache.commons.text.WordUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/***
* @author wangwei
* @date 2025-09-10
* 上下文获取bean
* 使用场景:
* 1.非 Spring 管理的类中使用 Spring Bean,当需要在普通 Java 类(未被@Component、@Service等注解标记的类)中使用 Spring 管理的 Bean 时,可以通过该工具类获取
*2.静态方法中使用 Spring Bean:静态方法中使用 Spring Bean
* 3.优先推荐使用依赖注入(@Autowired、@Resource等)的方式获取 Bean,只有在确实无法使用依赖注入时才考虑使用此类
***/
@Component
//类获取 Spring 的应用上下文(ApplicationContext)
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.context = applicationContext;
}
/**
* 返回 Spring 应用上下文
*
* @return
*/
public static ApplicationContext getContext() {
return context;
}
/***
* getBean 根据 Bean 名称获取 Bean 实例
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
/***
* 根据 Bean 名称和类型获取指定类型的 Bean
* @param beanName
* @param requiredType
* @param <T>
* @return
*/
public static <T> T getBean(String beanName, Class<T> requiredType) {
return context.getBean(beanName, requiredType);
}
public static <T> T getBean(Class<T> requiredType) {
String simpleName = requiredType.getSimpleName();
String name = WordUtils.uncapitalize(simpleName);
T obj = null;
try {
obj = getBean(name, requiredType);
} catch (NoSuchBeanDefinitionException e) {
}
if (obj != null) {
return obj;
}
return context.getBean(requiredType);
}
}
SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);