使用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);
那么Web项目中如何获取ApplicationContext
1.
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
2.
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)
注:至于获取ServletContext对象,可以从request,session中获取,他们都有getServletContext()方法
3 写一个工具类实现ApplicationContextAware接口,并将这个加入到spring的容器(推荐)
package com.ylcf.before.ylcf.base.sys.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @author zhengyunfei * @create 2018-02-08-下午 21:34 **/ public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.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="springContextUtil" class="com.ncut.ssm.util.SpringContextUtil"></bean>
最后在普通类就可以这样调用