Bean 实例化的三种方式
<h2>配置文件</h2>
<pre><code class="language-java"> Bean Xml方式
<!-- 无参实例化对象 -->
<bean id="TestConstructOne" class="net.spring.ioc.testFactory.TestConstructOne"></bean>
<!-- 静态实例化 -->
<bean id="TestConstructTwo" class="net.spring.ioc.testFactory.TestConstructFactoryTwo"
factory-method="CreateConstruct"></bean>
<!-- 实例化工厂-->
<bean id="TestConstructFactory" class="net.spring.ioc.testFactory.TestConstructFactoryThree"></bean>
<bean id="TestConstructThree" factory-bean="TestConstructFactory" factory-method="CreateFactoryThree"></bean></code></pre>
<h2>控制器</h2>
<pre><code class="language-java"> @Test
/**
* 无参实例化对象
*/
public void TestConstructOne(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestConstructOne one = (TestConstructOne)applicationContext.getBean("TestConstructOne");
one.TestConstructOne();
}
@Test
/**
* 通过静态工厂类实现实例化
*/
public void TestConstructTwo(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestConstructTwo TestConstructTwo = (TestConstructTwo)applicationContext.getBean("TestConstructTwo");
TestConstructTwo.TestConstructTwo();
}
@Test
/**
* 工厂类实现实例化
*/
public void TestConstructThree(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestConstructThree TestConstruct =
(TestConstructThree)applicationContext.getBean("TestConstructThree");
TestConstruct.TestConstructThree();
}</code></pre>
<h2>Service</h2>
<pre><code class="language-java">/**
* 第一种采用无参构造方法
*/
public class TestConstructOne {
public void TestConstructOne(){
System.out.println("第一种采用无参构造方法------被创建了");
}
}
/**
* 静态工厂实例化方式
*/
public class TestConstructTwo {
public void TestConstructTwo(){
System.out.println("第二种采用静态实例化------被创建了");
}
}
/**
* 第三种 实例化工程
*/
public class TestConstructThree {
public void TestConstructThree(){
System.out.println("第三种 实例化工程--- 已被执行");
}
}</code></pre>
<h2>工厂</h2>
<pre><code class="language-java">/**
* 静态实例化工厂
*/
public class TestConstructFactoryTwo {
public static TestConstructTwo CreateConstruct(){
System.out.println("实例化队形正在被执行.......");
return new TestConstructTwo();
}
}
/**
* 实例化工厂
*/
public class TestConstructFactoryThree {
public TestConstructThree CreateFactoryThree(){
System.out.println("实例化队形正在被执行.......");
return new TestConstructThree();
}
}</code></pre>