Last active
June 9, 2022 09:49
-
-
Save joshlong/4abe8dd8bc7f29725e02017bf8aa763c to your computer and use it in GitHub Desktop.
an example demonstrating Spring's new `InjectionPoint` support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import org.springframework.beans.factory.InjectionPoint; | |
import org.springframework.beans.factory.ObjectFactory; | |
import org.springframework.context.annotation.AnnotationConfigApplicationContext; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.annotation.Scope; | |
import org.springframework.stereotype.Component; | |
@Configuration | |
public class TestApplication { | |
public static void main(String[] args) { | |
new AnnotationConfigApplicationContext(TestApplication.class); | |
} | |
@Component | |
public static class FooUser { | |
private final Foo foo; | |
public FooUser(Foo foo) { | |
this.foo = foo; | |
} | |
} | |
@Component | |
public static class FooPrototypeUser { | |
// if you have JSR 330 on the CLASSPATH you can use javax.inject.Provider instead | |
private final ObjectFactory<Foo> fooObjectFactory; | |
public FooPrototypeUser(ObjectFactory<Foo> fooObjectFactory) { | |
this.fooObjectFactory = fooObjectFactory; | |
for (int i = 0; i < 10; i++) { | |
System.out.println(this.fooObjectFactory.getObject()); | |
} | |
} | |
} | |
@Bean | |
@Scope("prototype") | |
Foo foo(InjectionPoint ip) { | |
System.out.println(String.format("annotated element: %s, member: %s, field name: %s, method parameter: %s, annotated element: %s, declared type: %s", | |
ip.getAnnotatedElement() != null ? ip.getAnnotatedElement().getClass().getName() : "", | |
ip.getMember() != null ? ip.getMember().getName() : "", | |
ip.getField() != null ? ip.getField().getName() : "", | |
ip.getMethodParameter() != null ? ip.getMethodParameter().getParameterName() : "", | |
ip.getAnnotatedElement() != null ? ip.getAnnotatedElement().getClass().getName() : "", | |
ip.getDeclaredType() != null ? ip.getDeclaredType().getName() : "")); | |
return new Foo(); | |
} | |
} | |
class Foo { | |
} | |
/* | |
prints the following, ten times with unique information: | |
annotated element: java.lang.reflect.Constructor, member: com.example.TestApplication$FooPrototypeUser, field name: , method parameter: fooObjectFactory, annotated element: java.lang.reflect.Constructor, declared type: org.springframework.beans.factory.ObjectFactory | |
.. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment