Spring管理时普通类访问Service接口的方法

本文介绍了一个实用的Spring应用上下文工具类SpringContextUtil,该工具类通过实现ApplicationContextAware接口来获取Spring容器中的bean实例。文章详细展示了如何在普通类中使用此工具类,并通过@Component注解将其纳入Spring管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先创建一个AppliactionContext的工具类实现ApplicationContextAware接口用于获得appliactionContext对象


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware{

     private static ApplicationContext applicationContext; 

        // 下面的这个方法是继承ApplicationContextAware重写的方法
        @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);
        }

        public static Object getBean(Class requiredType){
            return applicationContext.getBean(requiredType);
        }

        public static Object getBean(String name, Class requiredType)
                throws BeansException {
            return applicationContext.getBean(name, requiredType);
        }

        public static boolean containsBean(String name) {
            return applicationContext.containsBean(name);
        }

        public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
            return applicationContext.isSingleton(name);
        }

     }

**2.在Spring容器中进行注册bean 在applicationContext.xml配置文件中

<bean id="SpringContextUtil" class="com.fx.util.SpringContextUtil" scope="singleton"></bean>

3.在普通类上需要进行标识@Component或者@Service 进行SPring容器的管理
@Component
public class ChineseProverbServerHandler extends SimpleChannelInboundHandler {
**********
}

4.然后在普通类中 获得appliactionContext对象 可以通过.class或者bean的名称获得Service

    ApplicationContext applicationContext=SpringContextUtil.getApplicationContext();
    IUserService userService=(IUserService) applicationContext.getBean(IUserService.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值