A method annotated with @Lookup
tells Spring to return an instance of the method’s return type when we invoke it. Essentially, Spring will override our annotated method and use our method’s return type and parameters as arguments to BeanFactory#getBean(AAA.class)
.
Provider is certainly one way, though @Lookup is more versatile in some respects.
@Component
@Scope("prototype")
public class SchoolNotification {
// ... prototype-scoped state
}
@Component
public class StudentServices {
// ... member variables, etc.
@Lookup
public SchoolNotification getNotification() {
return null;
}
// ... getters and setters
}
@Test
public void whenLookupMethodCalled_thenNewInstanceReturned() {
// ... initialize context
StudentServices first = this.context.getBean(StudentServices.class);
StudentServices second = this.context.getBean(StudentServices.class);
assertEquals(first, second);
assertNotEquals(first.getNotification(), second.getNotification());
}
@Component
@Scope("prototype")
public class SchoolNotification {
private String name;
private Collection<Integer> marks;
public SchoolNotification(String name) {
// ... set fields
}
// ... getters and setters
public String addMark(Integer mark) {
this.marks.add(mark);
}
}
public abstract class StudentServices {
private Map<String, SchoolNotification> notes = new HashMap<>();
@Lookup
protected abstract SchoolNotification getNotification(String name);
public String appendMark(String name, Integer mark) {
SchoolNotification notification = notes.computeIfAbsent(name, exists -> getNotification(name)));
return notification.addMark(mark);
}
}
First, We treat SchoolNotification
a bit more like a Spring-aware method. It does this by implementing getSchoolNotification
with a call to beanFactory.getBean(SchoolNotification.class, name)
.
Second, we can sometimes make the @Lookup
annotated method abstract, like the above example.
Using abstract is a bit nicer-looking than a stub, but we can only use it when we don’t component-scan
or @Bean-manage
the surrounding bean:
@Test
public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() {
// ... initialize context
StudentServices services = context.getBean(StudentServices.class);
assertEquals("PASS", services.appendMark("Alex", 89));
assertEquals("FAIL", services.appendMark("Bethany", 78));
assertEquals("PASS", services.appendMark("Claire", 96));
}
Despite @Lookup‘s versatility, there are a few notable limitations:
1、@Lookup-annotated methods, like getNotification
, must be concrete when the surrounding class is component-scanned
. This is because component scanning skips abstract beans
.
2、@Lookup-annotated methods won’t work at all when the surrounding class is @Bean-managed
.
In those circumstances, if we need to inject a prototype bean into a singleton, we can look to Provider as an alternative.
参考:@Lookup Annotation in Spring