Bean的实例化
一.构造器实例化
One.class类:
public class One { public void say(){ System.out.println("我是构造器实例化"); } }
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-4.3.xsd"> <bean id="one" class="cn.chauncey.ioc.One"/> </beans>
Test.class测试类:
public class OneTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); One one = (One) applicationContext.getBean("one"); one.say(); } }
运行结果:
二.静态工厂方式实例化
Two.class接口:
public interface Two { public void say(); }
TwoImp接口的实现类:
public class TwoImpl implements Two { @Override public void say() { System.out.println("我是静态工厂实例化"); } }
MyBeanFactory.class类:
public class MyBeanFactory { public static TwoImpl createBean(){ return new TwoImpl(); } }
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-4.3.xsd"> <bean id="twoImpl" class="cn.chauncey.ioc.MyBeanFactory" factory-method="createBean"/> </beans>
TwoTest.class测试类:
public class TwoTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); TwoImpl two = (TwoImpl) applicationContext.getBean("twoImpl"); two.say(); } }
运行结果:
三.实例工厂方式实例化
Three.class类:
public class Three { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
MyBeanFactory.class类:
public class MyBeanFactory { public Three createBean(){ return new Three(); } }
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-4.3.xsd"> <bean id="myBeanFactory" class="cn.chauncey.ioc.MyBeanFactory"/> <bean id="three" factory-bean="myBeanFactory" factory-method="createBean"> <property name="name" value="我是实例工厂方式实例化"/> </bean> </beans>
ThreeTest.class测试类:
public class ThreeTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Three three = (Three) applicationContext.getBean("three"); System.out.println(three.getName()); } }
运行效果: