@Nong
Anuchit Prasertsang
from SoftPlus Family
Introduction
Spring Frameworkpublic class ConstructorInjection { private Dependency dep; public ConstructorInjection(Dependency dep) { this.dep = dep; } }
public class SetterInjection { private Dependency dep; public void setMyDependency(Dependency dep) { this.dep = dep; } }
import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; public class XmlConfigWithBeanFactory { public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml")); SomeBeanInterface b = (SomeBeanInterface) factory.getBean("nameOftheBean"); } }
HelloWorld hello = new mypackage.HelloWorld();
<bean id="hello" class="mypackage.HelloWorld"></bean>
HelloWorld hello = new mypackage.HelloWorld("Hello World");
<bean id="hello" class="mypackage.HelloWorld"> <constructor-arg value="Hello World"/> </bean>
HelloWorld hello = new mypackage.HelloWorld(); hello.setMessage("Hello World");
<bean id="hello" class="mypackage.HelloWorld"> <property name="message" value="Hello World"/> </bean>
HelloWorld hello = ... MessageService msgService = new mypackage.MessageService(); msgService.setMessageProvider(hello)
<bean id="hello" class="mypackage.HelloWorld"> ..... </bean> <bean id="msgService" class="mypackage.MessageService"> <property name="messageProvider" ref="hello"/> </bean>
<property name="addressList"> <list> <value>INDIA</value> <value>Pakistan</value> <value>USA</value> <value>USA</value> <value>INDIA</value> </list> </property>
<property name="addressSet"> <set> <value>INDIA</value> <value>Pakistan</value> <value>USA</value> <value>USA</value> </set> </property>
<property name="addressMap"> <map> <entry key="1" value="INDIA"/> <entry key="2" value="Pakistan"/> <entry key="4" value="USA"/> </map> </property>
<property name="addressProp"> <props> <prop key="one">INDIA</prop> <prop key="two">Pakistan</prop> <prop key="three">USA</prop> <prop key="four">USA</prop> </props> </property>
public class ExampleBean { public void init() { // do some initialization work } }
<bean id="exampleBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean { public void destroy() { // do some destruction work } }
<bean id="exampleBean" class="examples.ExampleBean" destroy-method="destroy"/>
<?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"> <context:annotation-config/> <!-- bean definitions go here --> </beans>