Bean Creation :
- Direct instantiation
- <bean id=“beanId” class=“className”>
- BeanFactory instantiation
- Same syntax but class is subclass of BeanFactory
- getObject() called to obtain Bean
- Static Factory
- <bean id=“beanId” class=“className" factory-method=" staticCreationMethod“>
- Instance Factory Method
- <bean id=“beanId” factory-bean=“existingBeanId" factory-method=“nonStaticCreationMethod">
- Beans may be singletons or “prototypes”
- Attribute singleton=“false” causes instantiation with each getBean() lookup
- Singleton is default
- XmlBeanFactory pre-instantiates singletons
- May be overridden on per-instance basis by lazy-init=“true”
- Beans may also be marked abstract, allowing reuse of attribute values through inheritance
Basic Bean Creation :
Lets start with a simple program about IoC.
Spring IoC Bean class :
package com.javastuff.spring;
public class SpringExample {
public String message = " Welcome to Javastuff ";
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
}
Spring IoC Container configuration file :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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="springExample" class="com.javastuff.spring.SpringExample" /> </beans>
Test Class :
package com.javastuff.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.javastuff.spring.SpringExample;
public class TestClass {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext(
"ApplicationContext.xml");
SpringExample se = (SpringExample) factory.getBean("springExample");
System.out.println(" Message : " + se.getMessage());
}
}
Output :
Message : Welcome to Javastuff
Posted in: