如何通过Swagger基于ApiModel示例值手动生成类实例
Hey there, I've tackled similar problems before, and here's a solid way to generate your SomeEvent instance using the example value from @ApiModelProperty without hardcoding it:
1. Add the Right Swagger Dependencies
First, make sure your project has the necessary Swagger core libraries to parse annotation metadata. For Maven, add these to your pom.xml (use the version compatible with your Spring Boot setup):
<dependency> <groupId>io.swagger</groupId> <artifactId>swagger-core</artifactId> <version>2.2.15</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>2.2.15</version> </dependency>
2. Build a Utility to Extract Examples & Create Instances
We'll use Swagger's ModelConverters to pull the example value from the annotation, then use reflection to instantiate the class. Here's a reusable utility class:
import io.swagger.models.Model; import io.swagger.models.properties.StringProperty; import io.swagger.v3.core.converter.ModelConverters; import java.lang.reflect.Constructor; public class SwaggerExampleInstanceGenerator { @SuppressWarnings("unchecked") public static <T> T generateFromExample(Class<T> targetClass) throws Exception { // Resolve the Swagger model metadata for the target class Model swaggerModel = ModelConverters.getInstance() .readAll(targetClass) .get(targetClass.getSimpleName()); // Extract the example value for the "eventType" property StringProperty eventTypeProperty = (StringProperty) swaggerModel.getProperties().get("eventType"); String exampleEventType = eventTypeProperty.getExample(); // Use reflection to call the constructor with the example value Constructor<T> constructor = (Constructor<T>) targetClass.getConstructor(String.class); return constructor.newInstance(exampleEventType); } }
3. Use the Utility in Your Code
Now you can dynamically create your SomeEvent instance like this:
// Somewhere in your service/controller code try { SomeEvent dynamicEvent = SwaggerExampleInstanceGenerator.generateFromExample(SomeEvent.class); System.out.println(dynamicEvent.getEventType()); // Outputs: MY_EVENT } catch (Exception e) { // Handle exceptions (e.g., missing constructor, annotation issues) e.printStackTrace(); }
4. Extending for More Complex Classes
If your class has multiple properties or nested objects:
- For multiple properties, map each Swagger property's example to the corresponding constructor parameter (match by name or type).
- For nested objects, recursively call the generator for each nested class type.
- If you're using SpringFox (the older Spring Swagger integration), swap out
ModelConverterswith SpringFox'sDocumentationPluginsManagerto resolve models.
This approach keeps your code in sync with the Swagger annotations—if you update the example value in @ApiModelProperty, the generated instance will automatically use the new value without any code changes.
内容的提问来源于stack exchange,提问作者Jacob G.

