我使用的是springboot+mybatisplus +mysql
1.创建一个SpringUtil工具类
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public final class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub if (SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; System.out.println("=============================================="+ "========ApplicationContext配置成功,在普通类可以通过调用ToolSpring.getAppContext()获取applicationContext对象,applicationContext=" + applicationContext + "=========="); } } public static ApplicationContext getApplicationContext() { return applicationContext; } //通过类名称获取Bean. public static Object getBean(String name) { return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } }
2.在启动类上面添加注解
@Import(SpringUtil.class) 依赖 import org.springframework.context.annotation.Import;
3.在普通类中使用SpringUtil创建service类
TestService testService = (TestService )SpringUtil.getBean(TestService.class); testService.save(testEntity);
这里强转了一下,我试了下不强转也没问题
此时就可以使用testService里的方法来和数据库交互了
原文地址:https://www.cnblogs.com/baobeiqi-e/p/11857245.html
时间: 2024-10-09 00:41:14