Let us create spring hello world example by following below steps:
1. Download spring jar files and add into project class path.
2. Create java class (bean).
3. Create spring configuration file which contains all bean configurations.
4. Create spring test class.
5. Load spring configuration file into Resource Interface object.
Syntax: Resource resource = new ClassPathResource(“spring configuration file”);
6. Create BeanFactory (Spring IOC container) object by reading spring configuration file through resource object.
Syntax: BeanFactory beanFactory = new XmlBeanFactory(resource);
7. Get bean object from beanFactory (spring ioc container) by passing beanId.
TestBean testBean = beanFactory.getBean(“testBeanId″);
2. Create java class (bean).
3. Create spring configuration file which contains all bean configurations.
4. Create spring test class.
5. Load spring configuration file into Resource Interface object.
Syntax: Resource resource = new ClassPathResource(“spring configuration file”);
6. Create BeanFactory (Spring IOC container) object by reading spring configuration file through resource object.
Syntax: BeanFactory beanFactory = new XmlBeanFactory(resource);
7. Get bean object from beanFactory (spring ioc container) by passing beanId.
TestBean testBean = beanFactory.getBean(“testBeanId″);
Note:
1. We can also use ApplicationContext object for getting bean object as:
Synyax:
Synyax:
2. Spring IOC container is responsible for creating bean objects and dependency injection.
3. Spring uses singleton design pattern for beans, so every spring bean is singleton class by default.
3. Spring uses singleton design pattern for beans, so every spring bean is singleton class by default.
Example explanation:
First create a java bean class named “HelloWorld.java” which have a propoerty userName and a method sayHello. Next create a spring configuration file which defines the bean and its properties. Here we define HelloWorld.java bean with id helloWorld. This id will be used later to get the bean object from ApplicationContext object. Next create the Test.java class as a main program. Framework creates the ApplicationContext object by using spring configuration file. Then get the HelloWorld bean object from ApplicationContext by using getBean() method. We have to pass beanId in the getBean() method. At the time of object creation IoC container sets the bean propoerties value defined in spring configuration file i.e. userName property value will be set to jai.
Example:
HelloWorld.java
applicationContext.java
Test.java
No comments:
Post a Comment