Dependency Injection
Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
This concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.
What are the different types of IoC (dependency injection)?
· Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
· Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Which DI would you suggest Constructor-based or setter-based DI?
Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.
What are the benefits of IOC?
· It minimizes the amount of code in your application.It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases. Loose coupling is promoted with minimal effort and least intrusive mechanism.IOC containers support eager instantiation and lazy loading of services.
What is Spring IoC container?
The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.
What are types of IoC containers? Explain them.
· Bean Factory container: This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
· Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
What is the difference between singleton and prototype bean?
Prototype scope = A new object is created each time it is
injected/looked up. It will use
new SomeClass()
each time.
Singleton scope = The same object is returned each time it
is injected/looked up. Here it will instantiate one instance
of
SomeClass
and then return it each time.
No comments:
Post a Comment