工具類獲取bean操作
阿新 • • 發佈:2018-11-09
我們做專案過程中,有時候在一些工具類中難免會操作資料庫。我們知道用原生態的sql,可以去實現,但是程式碼量太多還繁雜,如果可以引用一些封裝的類去處理會更好。呼叫我們的類,需要引入進來。那麼問題來了?怎麼引入呢
因為工具類大多數都是static,用平常的注入方式不好使,就需要特定的方式來處理。開始上程式碼
首先我們建立一個獲取bean的類,實現ApplicationContextAware 介面
package com.bonatone.common.mail.service.impl; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContextUtil implements ApplicationContextAware{ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } }
使用我們的getBean方法就能獲取到我們想要的呼叫的bean。
獲取到以後就可以去進行我們的操作。
在你需要的工具類中引入
DefaultService service = (DefaultService)SpringContextUtil.getBean("defaultService");