Spring中Bean实例化的几种方式
程序员文章站
2022-03-03 11:49:39
...
Bean实例化的几种方式
- 类构造方法实例化
- 工厂类静态方法实例化
- 工厂类普通方法实例化
新建包BeanInstance
新建普通类UserService.java
package BeanInstance;
import java.text.MessageFormat;
public class UserService {
public UserService(String username){
System.out.println(MessageFormat.format("我是{0}!",username));
}
public void greeting(String nickname) {
System.out.println(MessageFormat.format("你好,{0}!", nickname));
}
}
新建单元测试类BeanTest.java
import org.junit.Test;
public class BeanTest {
}
类构造方法实例化
进行单元测试BeanTest.java
@Test
public void classTest() {
/**
* 测试类直接实例化
*/
UserService userService = new UserService("猫头鹰");
userService.greeting("黑虎");
}
beanInstance.xml配置
<bean id="userServiceByConstruct" class="BeanInstance.UserService">
<constructor-arg name="username" value="夜莺"/>
</bean>
进行单元测试BeanTest.java
@Test
public void beanConstructTest() {
/**
* 测试类构造方法进行Bean实例化
*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInstance.xml");
UserService userService = (UserService) applicationContext.getBean("userServiceByConstruct");
userService.greeting("黑虎");
}
工厂类静态方法实例化Bean
新建工厂类StaticBeanFactory.java,并添加静态方法
package BeanInstance;
public class StaticBeanFactory {
public static UserService getUserService() {
return new UserService("土狼");
}
}
进行单元测试BeanTest.java
@Test
public void staticTest(){
/**
* 测试静态方法实例化
*/
UserService userService=StaticBeanFactory.getUserService();
userService.greeting("猎豹");
}
beanInstance.xml配置
<bean id="userServiceByStatic" class="BeanInstance.StaticBeanFactory" factory-method="getUserService"/>
进行单元测试BeanTest.java
@Test
public void beanStaticTest() {
/**
* 测试静态方法进行Bean实例化
*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInstance.xml");
UserService userService = (UserService) applicationContext.getBean("userServiceByStatic");
userService.greeting("猎豹");
}
工厂类普通方法实例化Bean
新建工厂类InstanceBeanFactory.java,并添加静态方法
package BeanInstance;
public class InstanceBeanFactory {
public UserService getUserService() {
return new UserService("二狗子");
}
}
beanInstance.xml配置
<bean id="instanceBeanFactory" class="BeanInstance.InstanceBeanFactory"/>
<bean id="userServiceByInstance" class="BeanInstance.UserService" factory-bean="instanceBeanFactory"
factory-method="getUserService"/>
进行单元测试BeanTest.java
@Test
public void beanInstanceTest() {
/**
* 测试实例方法进行Bean实例化
*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInstance.xml");
UserService userService = (UserService) applicationContext.getBean("userServiceByInstance");
userService.greeting("大英子");
}
配置总结
beanInstance.xml关键点
类构造方法实例化Bean
有参构造使用标签进行参数注入:constructor-arg
工厂类静态方法实例化Bean
只需声明工厂类,但需指定factory-method为获取类实例的方法
工厂类普通方法实例化Bean
需声明类及其工厂类,类Bean指定factory-bean为其工厂类,指定factory-method为其获取实例的方法
源码下载
[email protected]:Angryshark128/Practice.git
上一篇: 反射API操作泛型
下一篇: Spring Bean的实例化过程