解決spring boot中普通類中使用service爲null 的方法

我使用的是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

@Import(SpringUtil.class) 依賴 import org.springframework.context.annotation.Import;

3.在普通類中使用SpringUtil建立service類
 sql

TestService testService = (TestService )SpringUtil.getBean(TestService.class); testService.save(testEntity);


這裏強轉了一下,我試了下不強轉也沒問題
此時就可使用testService裏的方法來和數據庫交互了數據庫

相關文章
相關標籤/搜索