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

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);

猜你喜欢

转载自blog.csdn.net/zhang_cl_cn/article/details/79193133