Java/Spring/XML Bean

Материал из Java эксперт
Версия от 06:16, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Alias Bean Demo

       
File: context.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="name1" name="name2,name3,name4" class="java.lang.String"/>
    <alias name="name1" alias="namex1"/>
    <alias name="name1" alias="namex2"/>
</beans>

File: Main.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] a) {
    BeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    String s1 = (String) factory.getBean("name1");
    String s2 = (String) factory.getBean("name2");
    String s3 = (String) factory.getBean("name3");
    String s4 = (String) factory.getBean("name4");
    String s5 = (String) factory.getBean("namex1");
    String s6 = (String) factory.getBean("namex2");
    System.out.println((s1 == s2));
    System.out.println((s2 == s3));
    System.out.println((s3 == s4));
    System.out.println((s4 == s5));
    System.out.println((s5 == s6));
  }
}





Autowiring

       
File: context.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="a" class="A"/>
    <bean id="b" class="B"/>
    <bean id="byName" autowire="byName" class="MyClass"/>
    <bean id="byType" autowire="byType" class="MyClass"/>
    <bean id="constructor" autowire="constructor" class="MyClass"/>
    <bean id="autodetect" autowire="autodetect" class="MyClass"/>
</beans>

File: Main.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
    System.out.println("byName:");
    System.out.println(bf.getBean("byName"));
    System.out.println("byType:");
    System.out.println(bf.getBean("byType"));
    System.out.println("constructor:");
    System.out.println(bf.getBean("constructor"));
    System.out.println("autodetect:");
    System.out.println(bf.getBean("autodetect"));
  }
}
class A {
  @Override
  public String toString() {
    return getClass().getName();
  }
}
class B {
  @Override
  public String toString() {
    return getClass().getName();
  }
}
class MyClass {
  private B B;
  private B B2;
  private A A;
  public MyClass() {
    System.out.println("MyClass()");
  }
  public MyClass(B B) {
    System.out.println("MyClass(B)");
    this.B = B;
  }
  public MyClass(B B, A A) {
    System.out.println("MyClass(B, A)");
    this.B = B;
    this.A = A;
  }
  public void setDependency(A A) {
    System.out.println("MyClass.setDependency(A)");
    this.A = A;
  }
  public void setB(B B) {
    System.out.println("MyClass.setB(B)");
    this.B = B;
  }
  public void setB2(B B2) {
    System.out.println("MyClass.setB2(B)");
    this.B2 = B2;
  }
  public void setA(A A) {
    System.out.println("MyClass.setA(A)");
    this.A = A;
  }
  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append("MyClass");
    sb.append("{B=").append(B);
    sb.append(", B2=").append(B2);
    sb.append(", A=").append(A);
    sb.append("}");
    return sb.toString();
  }
}





Bean Lifecycle DisposableBean

       
File: Main.java
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
public class Main {
  public static void main(String[] args) throws Exception {
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(factory)));
    
  }
}
class ShutdownHook implements Runnable {
  private ConfigurableListableBeanFactory beanFactory;
  public ShutdownHook(ConfigurableListableBeanFactory beanFactory) {
      Assert.notNull(beanFactory, "The "beanFactory" argument must not be null.");
      this.beanFactory = beanFactory;
  }
  public void run() {
      this.beanFactory.destroySingletons();
  }
}
class DestructiveBeanI implements InitializingBean, DisposableBean {
  public void afterPropertiesSet() throws Exception {
  }
  public void destroy() {
      System.out.println("Destroying Bean");
  }
  @Override
  public String toString() {
      final StringBuilder sb = new StringBuilder();
      sb.append("DestructiveBean");
      return sb.toString();
  }
}

File: context.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="destructive" class="DestructiveBeanI">
        <property name="filePath" value="/tmp"/>
    </bean>
</beans>





Bean Lifecycle Initializing

       
File: context.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="simple1" class="SoutSimpleBean">
        <property name="person" value="A"/>
        <property name="value" value="my value"/>
    </bean>
</beans>

File: Main.java
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    System.out.println(factory.getBean("simple1"));
  }
}
class SoutSimpleBean extends SimpleBeanSupport {
  private String person;
  public void setPerson(String person) {
    this.person = person;
  }
  @Override
  public String toString() {
    return String.format("%s : \"%s\"", this.person, getValue());
  }
}
abstract class SimpleBeanSupport implements InitializingBean {
  private String value;
  public final void afterPropertiesSet() throws Exception {
  }
  public final void setValue(String value) {
    this.value = value;
  }
  protected final String getValue() {
    return this.value;
  }
}





Component Filter Assignable

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="bean">
        <context:include-filter type="annotation" expression="bean.Magic"/>
        <context:include-filter type="assignable" expression="bean.ruponentMarker"/>
        <context:include-filter type="aspectj" expression="* void bean.*Service*(..)"/>
    </context:component-scan>
</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext(
        "context.xml");
    String[] beanNames = ac.getBeanDefinitionNames();
    for (String beanName : beanNames) {
      System.out.println(beanName + ": " + ac.getBean(beanName));
    }
  }
}
File: Magic.java
package bean;

public @interface Magic {
}

File: MarkedBean.java
package bean;

public class MarkedBean implements ComponentMarker {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("MarkedBean");
        sb.append("{}");
        return sb.toString();
    }
}

File: SimpleBean.java
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.ruponent;
import org.springframework.util.ObjectUtils;
/**
 * @author janm
 */
@Magic
class SimpleBean {
    private Dependency dependency;
    @Autowired(required = true)
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SimpleBean");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{dependency=").append(dependency);
        sb.append("}");
        return sb.toString();
    }
}
@Component
class Dependency {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Dependency");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{}");
        return sb.toString();
    }
}

File: ComponentMarker.java
package bean;

public interface ComponentMarker {
}





component scan

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop.xsd">
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="bean">
        <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
    </context:component-scan>

</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.Helper;
import bean.HelperDemo;
public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext(
        "context.xml");
    HelperDemo hd1 = (HelperDemo) ac.getBean("helperDemo");
    hd1.someOperation();
    System.out.println(hd1);
    HelperDemo hd2 = (HelperDemo) ac.getBean("helperDemo");
    hd2.someOperation();
    System.out.println(hd2);
    Helper helper = (Helper) ac.getBean("helper");
    System.out.println(helper);
  }
}
File: Helper.java
package bean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.ruponent;
@Component("helper")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Helper {
    private int count;
    public void work() {
        this.count++;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Helper");
        sb.append("{count=").append(count);
        sb.append("}");
        return sb.toString();
    }
}

File: HelperDemo.java
package bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.ruponent;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class HelperDemo {
    @Autowired
    private Helper helper;
    public void setHelper(Helper helper) {
        this.helper = helper;
    }
    public void someOperation() {
        this.helper.work();
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("HelperDemo");
        sb.append("{helper=").append(helper);
        sb.append("}");
        return sb.toString();
    }
}





Component Scan and scope

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop.xsd">
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="bean">
        <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
    </context:component-scan>

</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.Helper;
import bean.HelperDemo;
public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext(
        "context.xml");
    HelperDemo hd1 = (HelperDemo) ac.getBean("helperDemo");
    hd1.someOperation();
    System.out.println(hd1);
    HelperDemo hd2 = (HelperDemo) ac.getBean("helperDemo");
    hd2.someOperation();
    System.out.println(hd2);
    Helper helper = (Helper) ac.getBean("helper");
    System.out.println(helper);
  }
}
File: Helper.java
package bean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.ruponent;
@Component("helper")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Helper {
    private int count;
    public void work() {
        this.count++;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Helper");
        sb.append("{count=").append(count);
        sb.append("}");
        return sb.toString();
    }
}

File: HelperDemo.java
package bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.ruponent;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class HelperDemo {
    @Autowired
    private Helper helper;
    public void setHelper(Helper helper) {
        this.helper = helper;
    }
    public void someOperation() {
        this.helper.work();
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("HelperDemo");
        sb.append("{helper=").append(helper);
        sb.append("}");
        return sb.toString();
    }
}





Custom InitializationMethod

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="numberClass"
       class="CustomInitializationMethodNumberClass" 
       init-method="initialize"/>
</beans>

File: Main.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    ConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    
    CustomInitializationMethodNumberClass bean = (CustomInitializationMethodNumberClass)beanFactory.getBean("numberClass");
    
    System.out.println(bean.getNumbers());
  }
}
class CustomInitializationMethodNumberClass {
  private List<String> numbers = new ArrayList<String>();
  public List<String> getNumbers() {
    return this.numbers;
  }
  public void initialize() throws Exception {
    if (this.numbers.size() < 3) {
      numbers.add("one");
      numbers.add("two");
      numbers.add("three");
    }
  }
}





dependency check Demo

       
File: context.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="target1" class="SimpleBean"
            dependency-check="simple">
        <property name="someInt" value="1"/>
    </bean>
    <bean id="target2" class="SimpleBean"
        dependency-check="objects">
        <property name="nestedSimpleBean" ref="nestedSimpleBean"/>
    </bean>
    <bean id="target3" class="SimpleBean"
        dependency-check="all">
        <property name="nestedSimpleBean" ref="nestedSimpleBean"/>
        <property name="someInt" value="1"/>
    </bean>
    <bean id="nestedSimpleBean" class="SimpleBean"/>
</beans>

File: Main.java
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
    System.out.println(bf.getBean("target1"));
    System.out.println(bf.getBean("target2"));
    System.out.println(bf.getBean("target3"));
  }
}
class SimpleBean {
  private int someInt;
  private SimpleBean nestedSimpleBean;
  public void setSomeInt(int someInt) {
    this.someInt = someInt;
  }
  public void setNestedSimpleBean(SimpleBean nestedSimpleBean) {
    this.nestedSimpleBean = nestedSimpleBean;
  }
  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append("SimpleBean");
    sb.append("{someInt=").append(someInt);
    sb.append(", nestedSimpleBean=").append(nestedSimpleBean);
    sb.append("}");
    return sb.toString();
  }
}





destroy method

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="numberClass"
        class="CustomDestroyMethodNumberClass"
        destroy-method="close"/>
</beans>

File: Main.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    ConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
        "context.xml"));
    CustomDestroyMethodNumberClass numberClass = (CustomDestroyMethodNumberClass) beanFactory
        .getBean("numberClass");
    beanFactory.destroySingletons();
    System.out.println(numberClass.getNumbers());
  }
}
class CustomDestroyMethodNumberClass {
  private List<String> numbers = new ArrayList<String>();
  public CustomDestroyMethodNumberClass() {
    this.numbers.add("one");
    this.numbers.add("two");
    this.numbers.add("three");
  }
  public List<String> getNumbers() {
    return this.numbers;
  }
  public void close() throws Exception {
    System.out.println("closing");
    this.numbers = null;
  }
}





Filtered By Annotation

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="bean">
        <context:include-filter type="annotation" expression="bean.Magic"/>
        <context:include-filter type="assignable" expression="bean.ruponentMarker"/>
        <context:include-filter type="aspectj" expression="* void bean.*Service*(..)"/>
    </context:component-scan>
</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext(
        "context.xml");
    String[] beanNames = ac.getBeanDefinitionNames();
    for (String beanName : beanNames) {
      System.out.println(beanName + ": " + ac.getBean(beanName));
    }
  }
}
File: ComponentMarker.java
package bean;

public interface ComponentMarker {
}

File: Magic.java
package bean;

public @interface Magic {
}

File: MarkedBean.java
package bean;

public class MarkedBean implements ComponentMarker {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("MarkedBean");
        sb.append("{}");
        return sb.toString();
    }
}

File: SimpleBean.java
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.ruponent;
import org.springframework.util.ObjectUtils;
/**
 * @author janm
 */
@Magic
class SimpleBean {
    private Dependency dependency;
    @Autowired(required = true)
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SimpleBean");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{dependency=").append(dependency);
        sb.append("}");
        return sb.toString();
    }
}
@Component
class Dependency {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Dependency");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{}");
        return sb.toString();
    }
}





HierarchicalBeanFactory Demo

       
File: injectdemo2-context.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="name" class="java.lang.String">
        <constructor-arg value="My Value 1"/>
    </bean>
    <bean id="injectSimpleParent" class="InjectSimpleDemo">
        <property name="name" ref="name"/>
        <property name="age" value="2"/>
        <property name="height" value="0.8"/>
        <property name="isProgrammer" value="false"/>
        <property name="ageInSeconds" value="63072000"/>
    </bean>
</beans>

File: injectdemo3-context.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="name" class="java.lang.String">
        <constructor-arg value="My value"/>
    </bean>
    <bean id="injectSimpleChild" class="InjectSimpleDemo">
        <property name="name" ref="name"/>
        <property name="age" value="2"/>
        <property name="height" value="0.8"/>
        <property name="isProgrammer" value="false"/>
        <property name="ageInSeconds" value="63072000"/>
    </bean>
    <bean id="injectSimpleChild2" class="InjectSimpleDemo">
        <property name="name">
            <ref parent="name"/>
        </property>
        <property name="age" value="2"/>
        <property name="height" value="0.8"/>
        <property name="isProgrammer" value="false"/>
        <property name="ageInSeconds" value="63072000"/>
    </bean>
</beans>

File: Main.java
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) {
    XmlBeanFactory parent = new XmlBeanFactory(new ClassPathResource("injectdemo2-context.xml"));
    XmlBeanFactory child = new XmlBeanFactory(new ClassPathResource("injectdemo3-context.xml"), parent);
    System.out.println(parent.getBean("injectSimpleParent"));
    System.out.println(child.getBean("injectSimpleChild"));
    System.out.println(child.getBean("injectSimpleChild2"));  }
}
class InjectSimpleDemo {
  private String name;
  private int age;
  private float height;
  private boolean isProgrammer;
  private Long ageInSeconds;
  public void setAgeInSeconds(Long ageInSeconds) {
    this.ageInSeconds = ageInSeconds;
  }
  public void setIsProgrammer(boolean isProgrammer) {
    this.isProgrammer = isProgrammer;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public void setHeight(float height) {
    this.height = height;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return String.format("Name: %s\nAge: %d\nAge in Seconds: %d\nHeight: %g\nIs Programmer?: %b",
        this.name, this.age, this.ageInSeconds, this.height, this.isProgrammer);
  }
}





implements BeanNameAware

File: context.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="logging" class="LoggingBean"/>
</beans>

File: Main.java
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    XmlBeanFactory factory = new XmlBeanFactory(
        new ClassPathResource("context.xml"));
    LoggingBean lb = (LoggingBean) factory.getBean("logging");
    lb.run();
  }
}
class LoggingBean implements BeanNameAware {
  private String name;
  public void setBeanName(String name) {
    this.name = name;
  }
  public void run() {
    System.out.println("Bean name is"" + this.name + "".");
  }
}





Inheritance Demo

       
File: context.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="parent" class="SimpleBean" abstract="true">
        <property name="name" value="Name 1"/>
    </bean>
    <bean id="bean1" class="SimpleBean" parent="parent">
        <property name="age" value="28"/>
    </bean>
    <bean id="bean2" class="SimpleBean" parent="parent"/>
</beans>

File: Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.ruponent;
public class Main {
  public static void main(String[] args) throws Exception {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
    System.out.println(bf.getBean("bean1"));
    System.out.println(bf.getBean("bean2"));
    
  }
}
class SimpleBean {
  private String name;
  private int age;
  public void setName(String name) {
      this.name = name;
  }
  public void setAge(int age) {
      this.age = age;
  }
  @Override
  public String toString() {
      final StringBuilder sb = new StringBuilder();
      sb.append("SimpleBean");
      sb.append("{name="").append(name).append("\"");
      sb.append(", age=").append(age);
      sb.append("}");
      return sb.toString();
  }
}





Link With DataSource

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName">
       <value>sun.jdbc.odbc.JdbcOdbcDriver</value>
   </property>
   <property name="url">
       <value>jdbc:odbc:test</value>
   </property>
   <property name="username">
       <value>root</value>
   </property>
   <property name="password">
       <value>sql</value>
   </property>
   </bean>
   <bean id="datacon" class="Dataconimpl">
      <property name="dataSource"><ref local="dataSource"/></property>
   </bean>
</beans>

File: Main.java
import javax.sql.DataSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    BeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    Dataconimpl bean1 = (Dataconimpl) factory.getBean("datacon");
  }
}
class Dataconimpl implements Datacon {
  private DataSource dataSource;
  public void setDataSource(DataSource ds) {
    dataSource = ds;
  }
  public DataSource dbcon() {
    return dataSource;
  }
}
interface Datacon {
  public DataSource dbcon();
}





Local Reference

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="weatherService" class="WeatherServiceImpl">
    <property name="weatherDao">
      <ref local="weatherDao"/>
    </property>
  </bean>
  <bean id="weatherDao" class="StaticDataWeatherDaoImpl">
  </bean>
</beans>

File: Main.java
import java.util.Date;
import java.util.GregorianCalendar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class Main {
  public static void main(String args[]) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
    WeatherService ws = (WeatherService) ctx.getBean("weatherService");
    Double high = ws.getHistoricalHigh(new GregorianCalendar(2004, 0, 1).getTime());
    System.out.println("High was: " + high);
  }
}
class StaticDataWeatherDaoImpl implements WeatherDao {
  public WeatherData find(Date date) {
    WeatherData wd = new WeatherData();
    wd.setDate((Date) date.clone());
    return wd;
  }
  public WeatherData save(Date date) {
    System.out.println("save");
    return null;
  }
  public WeatherData update(Date date) {
    System.out.println("update");
    return null;
  }
}
interface WeatherService {
  Double getHistoricalHigh(Date date);
}
class WeatherServiceImpl implements WeatherService {
  private WeatherDao weatherDao;
  public void setWeatherDao(WeatherDao weatherDao) {
    this.weatherDao = weatherDao;
  }
  public Double getHistoricalHigh(Date date) {
    return null;
  }
}
interface WeatherDao {
  WeatherData find(Date date);
  WeatherData save(Date date);
  WeatherData update(Date date);
}
class WeatherData {
  Date date;

  public Date getDate() {
    return date;
  }
  public void setDate(Date date) {
    this.date = date;
  }

}





Non Static Factory

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="nonStaticFactory" class="NonStaticFactory"/>
  <bean id="testBeanObtainedViaNonStaticFactory"
        factory-bean="nonStaticFactory" factory-method="getTestBeanInstance"/>
</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class Main {
  public static void main(String args[]) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
    TestBean testBeanObtainedViaStaticFactory = (TestBean) ctx
        .getBean("testBeanObtainedViaNonStaticFactory");
  
  
  }
}
class NonStaticFactory {
  public TestBean getTestBeanInstance() {
    return new TestBean();
  }
}

class TestBean {
   
  
}





Properties File Based Spring Bean

File: helloworld-context.properties
source.(class)=SimpleMessageData
destination.(class)=StdoutMessageReporter

File: Main.java
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] a) {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(bf);
    reader.loadBeanDefinitions(new ClassPathResource("helloworld-context.properties"));
    MessageData source = (MessageData) bf.getBean("source");
    MessageReporter destination = (MessageReporter) bf.getBean("destination");
    destination.write(source.getMessage());
  }
}
interface MessageService {
  void execute();
}
class DefaultMessageService implements MessageService {
  private MessageData source;
  private MessageReporter destination;
  public void execute() {
      this.destination.write(this.source.getMessage());
  }
  public void setSource(MessageData source) {
      this.source = source;
  }
  public void setDestination(MessageReporter destination) {
      this.destination = destination;
  }
}
interface MessageReporter {
  void write(String message);
}
interface MessageData {
  String getMessage();
}
class StdoutMessageReporter implements MessageReporter {
  public void write(String message) {
    System.out.println(message);
  }
}
class SimpleMessageData implements MessageData {
  private final String message;
  public SimpleMessageData() {
    this("Hello, world");
  }
  public SimpleMessageData(String message) {
    this.message = message;
  }
  public String getMessage() {
    return this.message;
  }
}





Reference another bean and set property

       
File: context.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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="encyclopedia" class="HardcodedEncyclopedia"/>
    <bean id="oracle" class="BookwormOracle">
        <property name="encyclopedia" ref="encyclopedia"/>
    </bean>

</beans>

File: Main.java
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] a) {
    XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
    Oracle oracle = (Oracle) bf.getBean("oracle");
    System.out.println("Meaning of life is " + oracle.defineMeaningOfLife());
  }
}
interface Oracle {
  String defineMeaningOfLife();
}
interface Encyclopedia {
  Long findLong(String entry);
  
}
class BookwormOracle implements Oracle {
  private Encyclopedia encyclopedia;
  public String defineMeaningOfLife() {
      Long ageOfUniverse = this.encyclopedia.findLong("AgeOfUniverse");
      Long constantOfLife = this.encyclopedia.findLong("ConstantOfLife");
      return String.valueOf(ageOfUniverse / constantOfLife);
  }
  public void setEncyclopedia(Encyclopedia encyclopedia) {
      this.encyclopedia = encyclopedia;
  }
}

class HardcodedEncyclopedia implements Encyclopedia {
  private Map<String, Long> entryValues = new HashMap<String, Long>();
  public HardcodedEncyclopedia() {
      this.entryValues.put("AgeOfUniverse", 13700000000L);
      this.entryValues.put("ConstantOfLife", 326190476L);
  }
  public Long findLong(String entry) {
      return this.entryValues.get(entry);
  }
}





Serach By Base Package

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="bean"/>
</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml");
    System.out.println(ac.getBean("simplestBean"));
  }
}
File: Magic.java
package bean;

public @interface Magic {
}

File: MarkedBean.java
package bean;

public class MarkedBean implements ComponentMarker {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("MarkedBean");
        sb.append("{}");
        return sb.toString();
    }
}

File: SimpleBean.java
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.ruponent;
import org.springframework.util.ObjectUtils;
/**
 * @author janm
 */
@Magic
class SimpleBean {
    private Dependency dependency;
    @Autowired(required = true)
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SimpleBean");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{dependency=").append(dependency);
        sb.append("}");
        return sb.toString();
    }
}
@Component
class Dependency {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Dependency");
        sb.append(ObjectUtils.identityToString(this));
        sb.append("{}");
        return sb.toString();
    }
}

File: SimplestBean.java
package bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.ruponent;
/**
 * @author janm
 */
@Component("simplestBean")
@Scope("prototype")
public class SimplestBean {
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SimplestBean");
        sb.append("{}");
        return sb.toString();
    }
}

File: ComponentMarker.java
package bean;

public interface ComponentMarker {
}





Static Factory

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="testBeanObtainedViaStaticFactory"
        class="StaticFactory" factory-method="getTestBeanInstance"/>

</beans>

File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class Main {
  public static void main(String args[]) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
    TestBean testBeanObtainedViaStaticFactory = (TestBean) ctx
        .getBean("testBeanObtainedViaStaticFactory");
  
  
  }
}
class StaticFactory {
  public static TestBean getTestBeanInstance() {
    return new TestBean();
  }
}
class TestBean {
   
  
}





throw RequiredPropertyNotSetException

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="nameClass"
         class="InitializingBeanNameClass"/>
</beans>

File: Main.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("context.xml"));
    InitializingBeanNameClass nameClass = (InitializingBeanNameClass) beanFactory
        .getBean("nameClass");
    System.out.println(nameClass.getFirstName());
  }
}
class InitializingBeanNameClass implements InitializingBean {
  private String firstName;
  public String getFirstName() {
    return this.firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public void afterPropertiesSet() throws Exception {
    if (this.firstName == null) {
      throw new Exception("firstName property is required.");
    }
  }
}





XML Bean Injection

File: context.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="injectSimpleDemo" 
          class="InjectSimpleDemo"
          p:age="35" 
          p:ageInSeconds="1103760000" 
          p:height="1.79" 
          p:isProgrammer="false"/>
</beans>

File: Main.java
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) {
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
        "context.xml"));
    InjectSimpleDemo simple = (InjectSimpleDemo) factory.getBean("injectSimpleDemo");
    System.out.println(simple);
  }
}
class InjectSimpleDemo {
  private String name;
  private int age;
  private float height;
  private boolean isProgrammer;
  private Long ageInSeconds;
  public void setAgeInSeconds(Long ageInSeconds) {
    this.ageInSeconds = ageInSeconds;
  }
  public void setIsProgrammer(boolean isProgrammer) {
    this.isProgrammer = isProgrammer;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public void setHeight(float height) {
    this.height = height;
  }
  public void setName(String name) {
    this.name = name;
  }
  @Override
  public String toString() {
    return String.format("Name: %s\nAge: %d\nAge in Seconds: %d\nHeight: %g\nIs Programmer?: %b",
        this.name, this.age, this.ageInSeconds, this.height, this.isProgrammer);
  }
}