- Spring IOC is a Spring core container which is pretty much used in every Spring Application.
- Spring IOC container automatically creates all the Spring Beans which are backbone of our application.
- Spring's Inversion of control is nothing but framework is creating taking control to create object for us.
- It not only creates objects it manages them too and when needed the container is also going to wire them together,configure them which is also called as Dependency Injection.
- It manages their complete life-cycle from creation till destruction.
- Spring IOC too manages the Bean Life-cycle and helps developer to concentrate on writing the business logic.
- In a config file we mention all the classes in which we want to create the objects for.
- Spring has an independent IOC container which reads our config file and creates objects of all the listed classes.
- These objects are managed inside the container.
- The objects which Spring creates are called as bean.
- getBean("beanid",<type>) is used to get the object of the class.
- There are 2 types of IOC containers
- Bean Factory
- It is an interface.
- Application Context
- It is an interface.
- ClasspathXmlApplicationContext(implements this class)
- ApplicationContext is an extension to BeanFactory.
- It can do all the work of BeanFactory with some advanced features.
- ClassPathXMLApplicationContext implements ApplicationContext
- Framework creates objects for us and also injects dependencies
- We can configure application from configuration files.
Lifecycle Methods of Bean
- Spring IOC provides two important methods to every bean
- Public void init()
- Init method is used to initialise code , Loading configuration, connecting to DB, web services, et cetera.
- Public void destroy()
- Destroy is used to clean up code.
- We can change the name of these method, but the signature must remain the same.
- Spring container provides the configuration for these for this. It requires following inputs.
- Spring bean
- Configuration XML file.
- Spring container creates the object of bean and instantiates it with required values.
- Spring container calls, then the init method.
- Now we can fetch and use the bean from spring container.
- Spring calls destroy to clean up the initialised variables and configurations just before destroying the bean.
- We can configure these methods using following techniques
- XML
- Spring interface
- Annotation
Implementing Bean Lifecycle using interfaces
- We can implement bean lifecycle Using interfaces such as initialising bean and disposable bean.
- InitialisingBean provides a method which is used to initialise the bean. We need to implement this interface and override the method.
- DisposableBean Provides a method which is used to dispose of a bean We need to implement this interface and override method.
Implementing Bean Life cycle methods using annotations
- We use @PostConstruct And @PreDestroy
- Post construct is called after properties have been initialised
- Pre destroy is called before disposing of the bean.
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="airtel" class="com.springmvcimplant.ioc.entities.Airtel"></bean>
<bean id="voda" class="com.springmvcimplant.ioc.entities.Vodafone"></bean>
<bean id="sim" class="com.springmvcimplant.ioc.entities.Jio"></bean>
</beans>
HomeController.xml
package com.springmvcimplant.ioc.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springmvcimplant.ioc.entities.Airtel;
import com.springmvcimplant.ioc.entities.Vodafone;
import com.springmvcimplant.ioc.interfaces.Sim;
@Controller
public class HomeController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping("/")
@ResponseBody
public String home(HttpServletRequest request,Model model)
{
// System.out.println(request.getContextPath());
// ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
Airtel air=(Airtel)applicationContext.getBean("airtel");
air.calling();
air.data();
Vodafone v=applicationContext.getBean("voda",Vodafone.class);
v.calling();
v.data();
Sim s1=applicationContext.getBean("sim",Sim.class);
s1.calling();
s1.data();
return "Config Loaded";
}
@RequestMapping("/home")
public String myhome()
{
return "home";
}
}
See How we initialized a new Service provider "Jio" directly from Sim interface in code just by changing the class name in bean itself.
So by using interfaces we can inverse the control of creating objects to Framework itself.
Dependency Injection
- Dependency Injection is a design pattern that removes dependency from a programming code so that it is easy to manage and test the application.
- Dependency Injection makes our programming code loosely coupled.
- The dependencies are handled to the when its created.
- The dependencies are automatically feeded at the time of object creation
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wb" class="com.springmvc.WelcomeBean">
<property name="message" value="Welcome to Spring"></property>
</bean>
</beans>
ClientLogic.java package com.springmvc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class ClientLogic {
public static void main(String args[])
{
Resource res=new ClassPathResource("spconfig.xml");
BeanFactory factory=new XmlBeanFactory(res);
WelcomeBean wb=(WelcomeBean) factory.getBean("wb");
wb.show();
//Since BeanFactory IOC container is depricated now we use ApplicationContext as follows
ApplicationContext context=new ClassPathXmlApplicationContext("spconfig.xml");
WelcomeBean wb1=context.getBean("wb",WelcomeBean.class);
wb1.show();
}
}
WelcomeBean.java package com.springmvc;
public class WelcomeBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void show()
{
System.out.println(message);
}
}
Examples
No comments:
Post a Comment