使用Spring框架,我們不需要創建類的對象,都有Spring 容器創建,並通過注解來注入。注入的原理就是在程序啟動的時候,Spring根據xml中配置的路徑來掃描類,如果發現類的上方有類似@Service,@Controller,此時就會定位到當前類,然后來給當前類中標有注解的屬性進行注入,從而我們可以使用該屬性,調用方法。
那么普通類怎么使用@Service標記的方法呢?
1.如果你想用@autowired,那么這個類本身也應該是在spring的管理下 的,即你的UserLogUtil也要標注為一個component(或Service),這樣spring才知道要注入依賴;
2. 如果不標注為@Component的話,此時不能通過@autowired來注入依賴,只能通過ApplicationContext來取得標注為Service的類:
UserLogService service = ApplicationContext.getBean(UserLogService.class);
寫一個工具類實現ApplicationContextAware接口,並將這個加入到spring的容器(推薦)
public class JsonDataUtil implements ApplicationContextAware { /** * 實現ApplicationContextAware接口,並將這個加入到spring的容器 */ private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { JsonDataUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static Object getBean(String beanName){ return applicationContext.getBean(beanName); } public static Object getBean(Class c){ return applicationContext.getBean(c); }
然后將此bean注冊到spring 的容器中,在spring的配置文件添加如下代碼
<bean id="JsonDataUtil" class="com.powerbridge.utils.JsonDataUtil"></bean>
最后在普通類就可以這樣調用
ApplicationContext appCtx = JsonDataUtil.getApplicationContext(); WorkSpaceService workSpaceService = (WorkSpaceService)JsonDataUtil.getBean(WorkSpaceService.class);