参考文献

常用

自定义拦截器

  • Spring MVC拦截器的顶层接口是:HandlerInterceptor,包含三个方法:

    • preHandle 目标方法执行前执行
    • postHandle 目标方法执行后执行
    • afterCompletion 请求完成时执行
  • 一般情况会用HandlerInterceptor接口的实现类HandlerInterceptorAdapter类。

  • SpringMVC-过滤器,拦截器,监听器

获取Spring容器对象

BeanFactoryAware接口

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class TestService implements BeanFactoryAware {
private BeanFactory beanFactory;

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}

public void test() {
Test test = (Test) beanFactory.getBean("test");
}
}

ApplicationContextAware接口

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class TestService implements ApplicationContextAware {
private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

public void test() {
Test test = (Test) beanFactory.getBean("test");
}
}

ApplicationListener接口

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class TestService implements ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
applicationContext = event.getApplicationContext();
}

public void test() {
Test test = (Test) beanFactory.getBean("test");
}
}

初始化方法

  • 目前Spring中使用比较多的初始化Bean的方法有:

    • 使用@PostConstruct注解

    • 实现InitializingBean接口

不常用

BeanFactory扩展

  • BeanFactoryPostProcessor
  • BeanDefinitionRegistryPostProcessor