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个作用域
Employee emp=context.getBean(“Employee”)代码>
将返回一个新实例
@Scope(“prototype”)
提供了供参考的示例代码使用这种依赖项注入,我们将实现什么?您希望在Spring中这样做,而您已经有了Decent DI??为什么?您知道您可以使用
@Autowired
对吗?@antoniosss:Autowired太没用了,您怎么知道一个接口必须绑定什么类型,以及如果它必须是单例的或每个会话实例化一次呢。@TusharBanne:每个会话、每个请求进行开发,和单身汉binding@Arrr您有@SessionScope
@requestscope
原型
和默认的@Singleton
。你还需要什么?