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

使用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后面什么也没有

@Service
public class UserServiceImpl implements UserService {

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

  • 11
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值