我使用的是springboot+mybatisplus +mysql
1.建立一個SpringUtil工具類mysql
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.在啓動類上面添加註解spring
3.在普通類中使用SpringUtil建立service類
sql
這裏強轉了一下,我試了下不強轉也沒問題
此時就可使用testService裏的方法來和數據庫交互了數據庫