The Spring Inversion of Control (IOC) container has three main logical components: a registry (called the ApplicationContext
) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context. and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.
The IoC container isnt't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new
, the JVM instantiates a copuy of the new object and hands it straight to you - it never goes through the configuration process. There are three ways that you can get your beans configured.
Inject your beans
The most preferable opetion is to let Spring autowire all of your beans; thie requires the least amount of code and is the most maintainable.
Use @Configurable
If you really need objects created with new
to be autowired, you can use the Spring Configurable
annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build and turning on Spring's runtime configuration handlers.
IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.