Learn how to inject a Spring bean into an ordinary object.
In a Spring application, injecting one bean into another bean is very common. However, sometimes it’s desirable to inject a bean into an ordinary object. For instance, we may want to obtain references to services from within an entity object.
Fortunately, achieving that isn’t as hard as it might look. The following sections will present how to do so using the @Configurable annotation and an AspectJ weaver.
This annotation allows instances of the decorated class to hold references to Spring beans.
Before covering the @Configurable annotation, let’s set up a Spring bean definition:
@Service
public class IdService {
private static int count;
int generateId() {
return ++count;
}
}
This class is decorated with the @Service annotation; hence it can be registered with a Spring context via component scanning.
Here’s a simple configuration class enabling that mechanism:
@ComponentScan
public class AspectJConfig {
}
In its simplest form, we can use @Configurable without any element:
@Configurable
public class PersonObject {
private int id;
private String name;
public PersonObject(String name) {
this.name = name;
}
// getters and other code shown in the next subsection
}
The @Configurable annotation, in this case, marks the PersonObject class as being eligible for Spring-driven configuration.
We can inject IdService into PersonObject, just as we would in any Spring bean:
@Configurable
public class PersonObject {
@Autowired
private IdService idService;
// fields, constructor and getters - shown in the previous subsection
void generateId() {
this.id = idService.generateId();
}
}
However, an annotation is only useful if recognized and processed by a handler. This is where AspectJ weaver comes into play. Specifically, the AnnotationBeanConfigurerAspect will act on the presence of @Configurable and does necessary processing.
#spring #java #developer