知识点④:在 Interceptor 中使用 @autowired 自动注入
2018-03-23 12:29
1326 查看
要使用 @autowired 自动注入,就需要知道该注解生效的条件
@autowired 合适生效,即什么时候可以使用 @autowired 注解
根据官方描述:You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
所以,我们只需要将我们的 Interceptor 注册为一个 bean ,就可以正常的使用@autowired注解了
方法多种多样,这里主要说明 springboot 中的使用方法:
a. 方法一:通过给方法添加 @Bean 注解,返回一个 Interceptor 的 Bean,该 Interceptor 就可以正常的使用 @autowired 了
例:
拦截器类:
拦截器配置类:
@autowired 合适生效,即什么时候可以使用 @autowired 注解
根据官方描述:You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
所以,我们只需要将我们的 Interceptor 注册为一个 bean ,就可以正常的使用@autowired注解了
方法多种多样,这里主要说明 springboot 中的使用方法:
a. 方法一:通过给方法添加 @Bean 注解,返回一个 Interceptor 的 Bean,该 Interceptor 就可以正常的使用 @autowired 了
例:
拦截器类:
public class PermissionInterceptor extends HandlerInterceptorAdapter { @Autowired private PortalUserService userService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; } //使用 userService return true; } }
拦截器配置类:
@Configuration public class WebMVCConfig extends WebMvcConfigurerAdapter { //在此处,将拦截器注册为一个 Bean @Bean public PermissionInterceptor permissionInterceptor() { return new PermissionInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(permissionInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/swagger-resources/**") .excludePathPatterns("/v2/api-docs/**"); super.addInterceptors(registry); } }
相关文章推荐
- 使用反射机制调用service层方法Autowired标签自动注入失败
- Interceptor无法用Autowired自动注入Bean
- Spring MVC中使用@Autowired实现自动注入
- 关于Struts在Spring中使用autowired 自动注入的问题
- 关于Struts在Spring中使用autowired 自动注入的问题
- spring 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入
- 使用Spring的@Autowired 实现DAO, Service, Controller三层的注入
- 关于@Autowired自动注入属性为空
- 使用@Autowired自动装配bean
- Spring使用@Resource、@Autowired注入时出现空指针问题的原因
- 如何解决SpringBoot JpaRepository @Autowired 没法自动注入的问题
- @Autowired自动注入实例
- spring boot 中@Autowired注解无法自动注入的错误
- Idea springBoot配置器中 @Configuration 注解中使用 Autowired 注入报错
- spring注入之使用标签 @Autowired @Qualifier
- spring注入之使用标签 @Autowired @Qualifier
- Spring学习(六)-----Spring使用@Autowired注解自动装配
- 2.spring boot热启动,autowired自动加载,value注解,属性注入
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- Spring Boot @Autowired 没法自动注入的问题