Dynamic JSON Field Control in Spring Boot Without Code Changes: Jackson + ByteBuddy Mixin Composition
This article demonstrates how to dynamically control JSON serialization in Spring Boot 3.5.0 by combining Jackson mixins with ByteBuddy-generated interfaces, enabling per-class and global serialization rules without modifying DTOs or writing repetitive configuration.
Reading font
1. Introduction
In daily development, API responses often need scenario-specific JSON adjustments: hiding sensitive fields, reordering properties, or applying common transformations. The typical approach adds Jackson annotations directly on DTOs or defines separate mixin classes per type. As DTO count grows and business rules change, maintaining annotations and mixins per class becomes cumbersome. This article shows how to combine Jackson and ByteBuddy to apply multiple serialization rules flexibly without touching original DTOs.
2. Practical Implementation
2.1 Define Annotations
Two annotations drive the mechanism: @MixinClass — placed on a target class (e.g., a DTO) to declare which mixin interfaces apply specifically to that class. The value() array accepts interface classes only. @EnableMixinClass — placed on a configuration or bootstrap class to enable auto-scanning. It supports basePackages / value for scan paths and mixinClasses for global mixins applied to every scanned class.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MixinClass {
Class<?>[] value() default {};
}@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(MixinClassScanner.class)
public @interface EnableMixinClass {
@AliasFor("basePackages")
String[] value() default {};
@AliasFor("value")
String[] basePackages() default {};
Class<?>[] mixinClasses() default {};
}2.2 Auto-Scanning
MixinClassScannerimplements ImportBeanDefinitionRegistrar. During component scan it:
Reads @EnableMixinClass attributes ( basePackages, mixinClasses).
Uses ClassPathBeanDefinitionScanner with an AnnotationTypeFilter for HttpExchange (marker for scannable classes).
Overrides isCandidateComponent to accept only concrete, independent classes.
In registerBeanDefinition, merges global mixinClasses with any @MixinClass found on the scanned class, filters to interfaces, deduplicates, and registers the target class with its combined mixin list into MixinClassFactory.
Registers a singleton MixinClassFactory bean named "mixinClassFactory".
public class MixinClassScanner implements ImportBeanDefinitionRegistrar {
private final Environment environment;
public MixinClassScanner(Environment environment) { this.environment = environment; }
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
register(importingClassMetadata, registry, getPackagesToScan(importingClassMetadata));
}
private void register(AnnotationMetadata metadata, BeanDefinitionRegistry registry, Set<String> packagesToScan) {
MixinClassFactory factory = new MixinClassFactory();
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableMixinClass.class.getName()));
Class<?>[] mixinClasses = attributes.getClassArray("mixinClasses");
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false) {
@Override
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
BeanDefinition beanDefinition = definitionHolder.getBeanDefinition();
if (beanDefinition instanceof ScannedGenericBeanDefinition sbd) {
Class<?>[] allMixins = mixinClasses;
Map<String, Object> mixinClassAttr = sbd.getMetadata().getAnnotationAttributes(MixinClass.class.getName());
if (mixinClassAttr != null) {
Class<?>[] privateMixinClasses = (Class<?>[]) mixinClassAttr.get("value");
allMixins = Stream.concat(Arrays.stream(allMixins), Arrays.stream(privateMixinClasses))
.filter(Class::isInterface)
.distinct()
.toArray(Class[]::new);
}
factory.registerClassMixins(sbd.getMetadata().getClassName(), Arrays.asList(allMixins));
}
}
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return metadata.isIndependent() && metadata.isConcrete();
}
};
scanner.addIncludeFilter(new AnnotationTypeFilter(HttpExchange.class));
for (String pkg : packagesToScan) scanner.scan(pkg);
AbstractBeanDefinition mixinFactoryBean = BeanDefinitionBuilder.rootBeanDefinition(MixinClassFactory.class, () -> factory).getBeanDefinition();
registry.registerBeanDefinition("mixinClassFactory", mixinFactoryBean);
}
private Set<String> getPackagesToScan(AnnotationMetadata metadata) { ... }
}2.3 Factory Class
MixinClassFactoryholds a thread-safe map from target class to its mixin interface list:
public class MixinClassFactory {
private final Map<Class<?>, List<Class<?>>> classToMixins = new HashMap<>();
public Map<Class<?>, List<Class<?>>> getClassToMixins() { return Map.copyOf(classToMixins); }
public List<Class<?>> getMixins(Class<?> target) { List<Class<?>> mixins = classToMixins.get(target); return mixins == null || mixins.isEmpty() ? List.of() : List.copyOf(mixins); }
public void registerClassMixins(Class<?> target, List<Class<?>> mixins) { this.classToMixins.putIfAbsent(target, mixins); }
}2.4 Register Mixins into ObjectMapper
Jackson's ObjectMapper only allows one mixin per target class. To compose multiple mixins, a Jackson2ObjectMapperBuilderCustomizer bean dynamically generates a single interface that extends all required mixins using ByteBuddy, copies their type-level annotations, loads it into the target's class loader, and registers it as the combined mixin.
@Bean
Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(MixinClassFactory factory) {
return builder -> factory.getClassToMixins().forEach((target, mixinClasses) -> {
Class<?> combinedMixin = new ByteBuddy()
.makeInterface(mixinClasses)
.annotateType(collectTypeAnnotations(mixinClasses.toArray(new Class[0])))
.name("%s.mixin.%sCombinedMixin".formatted(target.getPackageName(), target.getSimpleName()))
.make()
.load(target.getClassLoader())
.getLoaded();
builder.mixIn(target, combinedMixin);
});
}
private List<Annotation> collectTypeAnnotations(Class<?>[] mixinClasses) {
List<Annotation> annotations = new ArrayList<>();
for (Class<?> mixin : mixinClasses) {
for (Annotation annotation : mixin.getAnnotations()) annotations.add(annotation);
}
return annotations;
}Without copying annotations from each mixin interface onto the generated combined interface, annotations like @JsonPropertyOrder or @JsonIgnore on the mixins would be lost.
2.5 Test Case
Two DTOs and two mixin interfaces demonstrate the composition:
@MixinClass({UserDTOMixin.class})
public class UserDTO {
private Long id;
private String username;
private String password;
private String phone;
private String idCard;
}
public class ProductDTO {
private Long id;
private String name;
private BigDecimal price;
private BigDecimal costPrice;
private String supplierPhone;
}@JsonPropertyOrder({"phone", "username"})
public interface UserDTOMixin {
@JsonIgnore String getPassword();
@JsonIgnore String getIdCard();
}
public interface CommonMixin {
@JsonIgnore Long getId();
}CommonMixinis registered globally via @EnableMixinClass on the application class:
@SpringBootApplication
@EnableMixinClass(basePackages = {"com.pack.business.dto"}, mixinClasses = {CommonMixin.class})
public class App {}Controllers return instances of UserDTO and ProductDTO. The serialized JSON output (shown in the article's screenshots) confirms: UserDTO — fields password and idCard are omitted (from UserDTOMixin), id is omitted (from global CommonMixin), and property order is phone, username (from @JsonPropertyOrder on UserDTOMixin). ProductDTO — only id is omitted (global CommonMixin); all other fields appear in default order.
This verifies that per-class mixins and global mixins compose correctly, and that ByteBuddy-generated combined interfaces preserve all annotations.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary