3.15 Bean Introspection
Since Micronaut 1.1, a compile-time replacement for the JDK’s Introspector class has been included.
The BeanIntrospector and BeanIntrospection interfaces allow looking up bean introspections to instantiate and read/write bean properties without using reflection or caching reflective metadata, which consume excessive memory for large beans.
Making a Bean Available for Introspection
Unlike the JDK’s Introspector, every class is not automatically available for introspection. To make a class available for introspection you must at a minimum enable Micronaut’s annotation processor (micronaut-inject-java
for Java and Kotlin and micronaut-inject-groovy
for Groovy) in your build and ensure you have a runtime time dependency on micronaut-core
.
annotationProcessor("io.micronaut:micronaut-inject-java:3.0.0")
<annotationProcessorPaths>
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-inject-java</artifactId>
<version>3.0.0</version>
</path>
</annotationProcessorPaths>
For Kotlin, add the micronaut-inject-java dependency in kapt scope, and for Groovy add micronaut-inject-groovy in compileOnly scope. |
runtime("io.micronaut:micronaut-core:3.0.0")
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-core</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Once your build is configured you have a few ways to generate introspection data.
Use the @Introspected
Annotation
The @Introspected annotation can be used on any class to make it available for introspection. Simply annotate the class with @Introspected:
import io.micronaut.core.annotation.Introspected;
@Introspected
public class Person {
private String name;
private int age = 18;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import groovy.transform.Canonical
import io.micronaut.core.annotation.Introspected
@Introspected
@Canonical
class Person {
String name
int age = 18
Person(String name) {
this.name = name
}
}
import io.micronaut.core.annotation.Introspected
@Introspected
data class Person(var name : String) {
var age : Int = 18
}
Once introspection data has been produced at compile time, retrieve it via the BeanIntrospection API:
final BeanIntrospection<Person> introspection = BeanIntrospection.getIntrospection(Person.class); (1)
Person person = introspection.instantiate("John"); (2)
System.out.println("Hello " + person.getName());
final BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String.class); (3)
property.set(person, "Fred"); (4)
String name = property.get(person); (5)
System.out.println("Hello " + person.getName());
def introspection = BeanIntrospection.getIntrospection(Person) (1)
Person person = introspection.instantiate("John") (2)
println("Hello $person.name")
BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String) (3)
property.set(person, "Fred") (4)
String name = property.get(person) (5)
println("Hello $person.name")
val introspection = BeanIntrospection.getIntrospection(Person::class.java) (1)
val person : Person = introspection.instantiate("John") (2)
print("Hello ${person.name}")
val property : BeanProperty<Person, String> = introspection.getRequiredProperty("name", String::class.java) (3)
property.set(person, "Fred") (4)
val name = property.get(person) (5)
print("Hello ${person.name}")
1 | You can retrieve a BeanIntrospection with the static getIntrospection method |
2 | Once you have a BeanIntrospection you can instantiate a bean with the instantiate method. |
3 | A BeanProperty can be retrieved from the introspection |
4 | Use the set method to set the property value |
5 | Use the get method to retrieve the property value |
Bean Fields
By default Java introspections treat only JavaBean getters/setters or Java 16 record components as bean properties. You can however define classes with public or package protected fields in Java using the accessKind
member of the @Introspected annotation:
import io.micronaut.core.annotation.Introspected;
@Introspected(accessKind = Introspected.AccessKind.FIELD)
public class User {
public final String name; (1)
public int age = 18; (2)
public User(String name) {
this.name = name;
}
}
import io.micronaut.core.annotation.Introspected
@Introspected(accessKind = Introspected.AccessKind.FIELD)
class User {
public final String name (1)
public int age = 18 (2)
User(String name) {
this.name = name
}
}
1 | Final fields are treated like read-only properties |
2 | Mutable fields are treated like read-write properties |
The accessKind accepts an array so it is possible to allow for both types of accessors but prefer one or the other depending on the order they appear in the annotation. The first one in the list has priority. |
Introspections on fields are not possible in Kotlin because it is not possible to declare fields directly. |
Constructor Methods
For classes with multiple constructors, apply the @Creator annotation to the constructor to use.
import io.micronaut.core.annotation.Creator;
import io.micronaut.core.annotation.Introspected;
import javax.annotation.concurrent.Immutable;
@Introspected
@Immutable
public class Vehicle {
private final String make;
private final String model;
private final int axles;
public Vehicle(String make, String model) {
this(make, model, 2);
}
@Creator (1)
public Vehicle(String make, String model, int axles) {
this.make = make;
this.model = model;
this.axles = axles;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getAxles() {
return axles;
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Vehicle {
final String make
final String model
final int axles
Vehicle(String make, String model) {
this(make, model, 2)
}
@Creator (1)
Vehicle(String make, String model, int axles) {
this.make = make
this.model = model
this.axles = axles
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Vehicle @Creator constructor(val make: String, val model: String, val axles: Int) { (1)
constructor(make: String, model: String) : this(make, model, 2) {}
}
1 | The @Creator annotation denotes which constructor to use |
This class has no default constructor, so calls to instantiate without arguments throw an InstantiationException. |
Static Creator Methods
The @Creator annotation can be applied to static methods that create class instances.
import io.micronaut.core.annotation.Creator;
import io.micronaut.core.annotation.Introspected;
import javax.annotation.concurrent.Immutable;
@Introspected
@Immutable
public class Business {
private final String name;
private Business(String name) {
this.name = name;
}
@Creator (1)
public static Business forName(String name) {
return new Business(name);
}
public String getName() {
return name;
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Business {
final String name
private Business(String name) {
this.name = name
}
@Creator (1)
static Business forName(String name) {
new Business(name)
}
}
import io.micronaut.core.annotation.Creator
import io.micronaut.core.annotation.Introspected
import javax.annotation.concurrent.Immutable
@Introspected
@Immutable
class Business private constructor(val name: String) {
companion object {
@Creator (1)
fun forName(name: String): Business {
return Business(name)
}
}
}
1 | The @Creator annotation is applied to the static method which instantiates the class |
There can be multiple “creator” methods annotated. If there is one without arguments, it will be the default construction method. The first method with arguments will be used as the primary construction method. |
Enums
It is possible to introspect enums as well. Add the annotation to the enum and it can be constructed through the standard valueOf
method.
Use the @Introspected
Annotation on a Configuration Class
If the class to introspect is already compiled and not under your control, an alternative option is to define a configuration class with the classes
member of the @Introspected annotation set.
import io.micronaut.core.annotation.Introspected;
@Introspected(classes = Person.class)
public class PersonConfiguration {
}
import io.micronaut.core.annotation.Introspected
@Introspected(classes = Person)
class PersonConfiguration {
}
import io.micronaut.core.annotation.Introspected
@Introspected(classes = [Person::class])
class PersonConfiguration
In the above example the PersonConfiguration
class generates introspections for the Person
class.
You can also use the packages member of the @Introspected which package scans at compile time and generates introspections for all classes within a package. Note however this feature is currently regarded as experimental. |
Write an AnnotationMapper
to Introspect Existing Annotations
If there is an existing annotation that you wish to introspect by default you can write an AnnotationMapper.
An example of this is EntityIntrospectedAnnotationMapper which ensures all beans annotated with javax.persistence.Entity
are introspectable by default.
The AnnotationMapper must be on the annotation processor classpath. |
The BeanWrapper API
A BeanProperty provides raw access to read and write a property value for a given class and does not provide any automatic type conversion.
It is expected that the values you pass to the set
and get
methods match the underlying property type, otherwise an exception will occur.
To provide additional type conversion smarts the BeanWrapper interface allows wrapping an existing bean instance and setting and getting properties from the bean, plus performing type conversion as necessary.
final BeanWrapper<Person> wrapper = BeanWrapper.getWrapper(new Person("Fred")); (1)
wrapper.setProperty("age", "20"); (2)
int newAge = wrapper.getRequiredProperty("age", int.class); (3)
System.out.println("Person's age now " + newAge);
final BeanWrapper<Person> wrapper = BeanWrapper.getWrapper(new Person("Fred")) (1)
wrapper.setProperty("age", "20") (2)
int newAge = wrapper.getRequiredProperty("age", Integer) (3)
println("Person's age now $newAge")
val wrapper = BeanWrapper.getWrapper(Person("Fred")) (1)
wrapper.setProperty("age", "20") (2)
val newAge = wrapper.getRequiredProperty("age", Int::class.java) (3)
println("Person's age now $newAge")
1 | Use the static getWrapper method to obtain a BeanWrapper for a bean instance. |
2 | You can set properties, and the BeanWrapper will perform type conversion, or throw ConversionErrorException if conversion is not possible. |
3 | You can retrieve a property using getRequiredProperty and request the appropriate type. If the property doesn’t exist a IntrospectionException is thrown, and if it cannot be converted a ConversionErrorException is thrown. |
Jackson and Bean Introspection
Jackson is configured to use the BeanIntrospection API to read and write property values and construct objects, resulting in reflection-free serialization/deserialization. This is beneficial from a performance perspective and requires less configuration to operate correctly with runtimes such as GraalVM native.
This feature is enabled by default; disable it by setting the jackson.bean-introspection-module
configuration to false
.
Currently only bean properties (private field with public getter/setter) are supported and usage of public fields is not supported. |
This feature is currently experimental and may be subject to change in the future. |