欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring学习-创建Bean的三种方式

程序员文章站 2022-05-24 18:23:04
...
MyTestInstance类

package com.app.impl;

public class MyTestInstance {

private String testMessage;

public MyTestInstance(){
System.out.println("初始化我的MyTestInstance类.");
}
public void info(){
System.out.println(this.getTestMessage());
}

public String getTestMessage() {
return testMessage;
}

public void setTestMessage(String testMessage) {
this.testMessage = testMessage;
}


}




TestCreateInstance 类

package com.app.impl;

import com.app.ICreateInstance;

public class TestCreateInstance implements ICreateInstance {

private String message;

public TestCreateInstance(){
System.out.println("使用构造器创建Bean实例");
}
public static MyTestInstance staticCreateInstance(){
MyTestInstance instance = new MyTestInstance();
System.out.println("使用静态工厂方法创建Bean");
return instance;
}
public MyTestInstance createInstance(){
MyTestInstance instance = new MyTestInstance();
System.out.println("调用实例工厂方法创建Bean");
return instance;
}

public void testService() {
System.out.println("testService--------------");
}

public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}




}




Hibernate.cfg.xml配置

<bean id="testCreateInstance1" class="com.app.impl.TestCreateInstance" p:message="我的哈哈">
</bean>
<bean id="testCreateInstance2" class="com.app.impl.TestCreateInstance"
p:testMessage="不是哈哈1"
factory-method="staticCreateInstance">
</bean>
<bean id="testCreateInstance3" factory-bean="testCreateInstance1"
p:testMessage="不是哈哈2"
factory-method="createInstance">
</bean>


测试

public void testCreate(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

TestCreateInstance instance1 = ctx.getBean("testCreateInstance1",TestCreateInstance.class);
instance1.testService();

MyTestInstance instance2 = ctx.getBean("testCreateInstance2",MyTestInstance.class);
instance2.info();

MyTestInstance instance3 = ctx.getBean("testCreateInstance3",MyTestInstance.class);
instance3.info();
}


输出:
---------------------------------------------------
使用构造器创建Bean实例
初始化我的MyTestInstance类.
使用静态工厂方法创建Bean
初始化我的MyTestInstance类.
调用实例工厂方法创建Bean
testService--------------
不是哈哈1
不是哈哈2