Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 使用拦截器注入依赖项_Spring_Spring Mvc - Fatal编程技术网

Spring 使用拦截器注入依赖项

Spring 使用拦截器注入依赖项,spring,spring-mvc,Spring,Spring Mvc,从技术上讲,使用拦截器类型注入所需的依赖项是否是一种良好且可接受的做法。例如: public @interface Inject { public Class thisType(); } public class InjectionInterceptor implements HandlerInterceptor { @Override public bool preHandle(HttpServletRequest hsr, HttpServletResponse

从技术上讲,使用
拦截器
类型注入所需的依赖项是否是一种良好且可接受的做法。例如:

public @interface Inject {
    public Class thisType();
}

public class InjectionInterceptor implements HandlerInterceptor {

    @Override
    public bool preHandle(HttpServletRequest hsr, HttpServletResponse hsr1, Object o) {
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Class type = handlerMethod.getBeanType();
        Annotation[] annotations =  type.getAnnotationsByType(Inject.class);
        for(Annotation annotation: annotations){
            Inject inject = (inject) annotation;
            for(Field field :type.getDeclaredFields()){
                if(field.getType().equals(inject.thisType())){
                    field.setAccessible(true);
                    field.set(handlerMethod.getBean(), Services.find(inject.thisType()));
                }
            }
            ....
      return true;
   }
   ...
}

一个bean可以有4个作用域

  • 独生子女 只有一个bean的共享实例将被管理,对于id或id与该bean定义匹配的bean的所有请求都将导致Spring容器返回一个特定的bean实例

    它是bean的默认范围

  • 原型 当请求具有指定id的bean时,容器将返回新实例

    例:如果在spring容器中有一个id为“employee”的bean,那么每次执行

    Employee emp=context.getBean(“Employee”)

    将返回一个新实例

  • 请求、会话和全局会话仅在基于web的应用程序中使用

  • 请求 为每个HTTP请求创建一个新实例。 例:每次登录都需要不同的实例

  • 会议 在单个HTTP会话的生存期内,将使用bean定义创建bean的新实例

  • 全球的 全局会话作用域类似于标准HTTP会话作用域,并且仅在基于portlet的web应用程序上下文中才有意义

  • 可以通过两种方式指定bean的作用域

  • 使用XML:
  • 使用注释

    @Scope(“prototype”)

  • 您可以阅读有关作用域的更多信息


    提供了供参考的示例代码

    使用这种依赖项注入,我们将实现什么?您希望在Spring中这样做,而您已经有了Decent DI??为什么?您知道您可以使用
    @Autowired
    对吗?@antoniosss:Autowired太没用了,您怎么知道一个接口必须绑定什么类型,以及如果它必须是单例的或每个会话实例化一次呢。@TusharBanne:每个会话、每个请求进行开发,和单身汉binding@Arrr您有
    @SessionScope
    @requestscope
    原型
    和默认的
    @Singleton
    。你还需要什么?