Spring 注解中,普通类获取@Service标记的方法 或者bean对象

来源:互联网 发布:软件企业评估管理办法 编辑:程序博客网 时间:2024/04/30 04:56

使用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.ncut.ssm.util;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** * @author Frank Yuan * @create 2017-05-02-下午 10:32 **/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>

最后在普通类就可以这样调用

ApplicationContext appCtx = SpringContextUtil.getApplicationContext();UserService bean = (UserService)SpringContextUtil.getBean("UserService");

或者

ApplicationContext appCtx = SpringContextUtil.getApplicationContext();UserService bean = (UserService)SpringContextUtil.getBean(UserService.class);

第一种情况适用于在@Service(“”UserService” “)标注了bean的名字

@Service("UserService")public class UserServiceImpl implements UserService {

第二种情况适用于在@Service后面什么也没有

@Servicepublic class UserServiceImpl implements UserService {

这种情况下不能使用UserServcieImpl.class,而是要用其接口类UserService.class,因为UserServiceImpl 没有被其他类注入过,会报找不到这个class

3 0