11 Common Spring Framework Extension Points
1. Type Converters
When receiving request parameters in Spring, you might encounter a scenario where a field in your entity is defined as Date but the incoming parameter is a String in format "2022-12-15 10:20:15". How do you handle this?
Spring provides the TypeConverter extension point with three variants:
Converter<S,T>: Converts objects from type S to type TConverterFactory<S, R>: Converts type S to type R or any of its subclassesGenericConverter: Supports multiple source and target types with contextual information derived from annotations or field metadata
Let's walk through a practical example:
- Define a user entity:
@Data
public class User {
private Long id;
private String name;
private Date registrationDate;
}
- Implement the
Converterinterface:
public class DateFormatConverter implements Converter<String, Date> {
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Date convert(String source) {
if (source != null && !source.isEmpty()) {
try {
return dateFormatter.parse(source);
} catch (ParseException e) {
log.error("Failed to parse date string: {}", source, e);
}
}
return null;
}
}
- Register the converter with Spring's formatter registry:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateFormatConverter());
}
}
- Controller endpoint that auto-converts the date:
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/save")
public String save(@RequestBody User user) {
return "success";
}
}
Now when the API receives a date string, Spring automatically converts it to a Date object.
2. Accessing the Spring Container Bean
During development, you often need to retrieve beans from the Spring container. Here's how to obtain the container object:
BeanFactoryAware
@Service
public class PersonService implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void add() {
Person person = beanFactory.getBean("person", Person.class);
}
}
By implementing BeanFactoryAware and overriding setBeanFactory, you can access the container directly.
ApplicationContextAware
@Service
public class PersonService2 implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void add() {
Person person = applicationContext.getBean("person", Person.class);
}
}
Implementing ApplicationContextAware provides similar access through the setApplicationContext method.
ApplicationListener
@Service
public class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
this.applicationContext = event.getApplicationContext();
}
public void add() {
Person person = applicationContext.getBean("person", Person.class);
}
}
3. Global Exception Handling
When developing APIs, exceptions need to provide user-friendly error messages. Consider this controller:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/calculate")
public String calculate() {
int a = 10 / 0;
return "result";
}
}
Without proper exception handling, users see raw error messages—an poor user experience.
You could wrap each endpoint in try-catch blocks:
@GetMapping("/calculate")
public String calculate() {
String result = "success";
try {
int a = 10 / 0;
} catch (Exception e) {
result = "error";
}
return result;
}
But with hundreds of endpoints, this becomes impractical. Use @RestControllerAdvice for centralized exception handling:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
if (e instanceof ArithmeticException) {
return "calculation error";
}
if (e instanceof IllegalArgumentException) {
return "invalid parameter";
}
return "internal error";
}
}
Now all endpoints have uniform exception handling without explicit try-catch in each method.
4. Custom Interceptors
Spring MVC interceptors provide access to HttpServletRequest and HttpServletResponse objects, enabling scenarios like authentication, authorization, logging, and metrics.
The core interface is HandlerInterceptor with three methods:
preHandle: Executed before the target methodpostHandle: Executed after the target method completesafterCompletion: Executed after the entire request finishes
Extend HandlerInterceptorAdapter for convenience:
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestUrl = request.getRequestURI();
if (validateAuthentication(requestUrl)) {
return true;
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
private boolean validateAuthentication(String requestUrl) {
// Authentication logic here
return true;
}
}
Register the interceptor:
@Configuration
public class WebAuthConfig extends WebMvcConfigurerAdapter {
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor());
}
}
Spring MVC will now automatically intercept requests and validate permissions.
5. Import Configuration
The @Import annotation allows importing classes into the Spring container. It supports four types:
5.1 Regular Class
public class ComponentA {
}
@Import(ComponentA.class)
@Configuration
public class ApplicationConfig {
}
Class ComponentA becomes a Spring-managed bean,injectable via @Autowired:
@Autowired
private ComponentA componentA;
5.2 Configuration Class
public class ComponentA {
}
public class ComponentB {
}
@Import(ComponentB.class)
@Configuration
public class ComponentAConfig {
@Bean
public ComponentA componentA() {
return new ComponentA();
}
}
@Import(ComponentAConfig.class)
@Configuration
public class ApplicationConfig {
}
Configuration classes support @Import, @ImportResource, and @PropertySource annotations recursively.
5.3 ImportSelector
public class ComponentAImportSelector implements ImportSelector {
private static final String CLASS_NAME = "com.example.config.ComponentA";
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{CLASS_NAME};
}
}
@Import(ComponentAImportSelector.class)
@Configuration
public class ApplicationConfig {
}
This approach returns an array, enabling multiple class imports.
5.4 ImportBeanDefinitionRegistrar
public class ComponentAImportRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(ComponentA.class);
registry.registerBeanDefinition("componentA", beanDefinition);
}
}
@Import(ComponentAImportRegistrar.class)
@Configuration
public class ApplicationConfig {
}
This offers maximum flexibility—you can programmatically create and register BeanDefinition instances.
6. Application Startup Tasks
Sometimes you need to execute logic when the application starts:loading configuration, initializing caches, or warming up resources.
SpringBoot provides two interfaces:
CommandLineRunnerApplicationRunner
Example using ApplicationRunner:
@Component
public class DataLoader implements ApplicationRunner {
@Autowired
private DataService dataService;
@Override
public void run(ApplicationArguments args) throws Exception {
dataService.initialize();
}
}
To control execution order among multiple runners, use @Order(n) where lower values execute first. Alternatively, @Priority annotation works similarly.
7. Modifying BeanDefinition
Before bean instantiation, Spring IOC reads bean metadata into BeanDefinition objects. To modify these properties programmatically, implement BeanFactoryPostProcessor:
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) beanFactory;
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
builder.addPropertyValue("id", 123);
builder.addPropertyValue("name", "Tom");
factory.registerBeanDefinition("user", builder.getBeanDefinition());
}
}
The postProcessBeanFactory method provides access to modify bean definitions before instantiation.
8. Pre and Post Bean Initialization
To execute custom logic before or after bean initialization, implement BeanPostProcessor:
postProcessBeforeInitialization: Called before initialization methodspostProcessAfterInitialization: Called after initialization methods
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof User) {
((User) bean).setUserName("Tom");
}
return bean;
}
}
Annotations like @Autowired, @Value, @Resource, and @PostConstruct are processed through AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor.
9. Initialization Methods
Spring supports multiple bean initialization strategies:
Using @PostConstruct
@Service
public class UserService {
@PostConstruct
public void initialize() {
System.out.println("=== initialization complete ===");
}
}
Implementing InitializingBean
@Service
public class AccountService implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("=== initialization complete ===");
}
}
10. Pre-Container Shutdown Hooks
To perform cleanup before Spring container destruction—releasing resources, closing connections—implement DisposableBean:
@Service
public class DatabaseService implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Resources released");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Initializing resources");
}
}
The destroy method exectues before the container shuts down. Typically, you implement both InitializingBean and DisposableBean for paired initialization and cleanup.
11. Custom Bean Scopes
Spring's default scopes include:
singleton: Same instance returned from containerprototype: New instance for each container retrieval
Web applications extend these with:
request: Same bean within one HTTP requestsession: Same bean within one HTTP session
For thread-bound instances, implement a custom scope:
public class ThreadLocalScope implements Scope {
private static final ThreadLocal<Object> THREAD_SCOPE = new ThreadLocal<>();
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Object value = THREAD_SCOPE.get();
if (value != null) {
return value;
}
Object instance = objectFactory.getObject();
THREAD_SCOPE.set(instance);
return instance;
}
@Override
public Object remove(String name) {
THREAD_SCOPE.remove();
return null;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return null;
}
}
Register the custom scope:
@Component
public class ThreadLocalScopeBeanProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerScope("threadLocalScope", new ThreadLocalScope());
}
}
Use the custom scope:
@Scope("threadLocalScope")
@Service
public class UserService {
public void execute() {
}
}