Spring实例化Bean的方式
程序员文章站
2022-05-21 15:05:52
...
Spring实例化Bean的方式有三种:
- 默认构造
- 静态工厂
- 实例工厂
1. 默认构造方式
目标类和接口:
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("add User");
}
}
配置文件:
<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="userService" class="com.scong.a_ioc.UserServiceImpl"></bean>
</beans>
注:默认构造方式目标类中一定要有无参的构造方法(即:当存在有参的构造方法时,一定要写无参构造方法),在配置文件中一般以<bean id="" class="">方式配置。
2. 静态工厂
静态工厂的配置除了要指定全限定类名以外,还要配置静态方法。
例:(上面的类不变)
添加工厂类
public class MyBeanFactory {
public static UserService createService(){
return new UserServiceImpl();
}
}
修改配置文件,配置工厂全限定类名和工厂静态方法名。
<?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">
<!-- 配置静态工厂
class:工厂的全限定类名
factory-method:工厂的静态方法名
-->
<bean id="userService" class="com.scong.c_ioc_staticfacotry.MyBeanFactory"
factory-method="createService"></bean>
</beans>
测试:
public class TestStaticFactory {
//手动创建方式
@Test
public void demo01(){
UserService userService = MyBeanFactory.createService();
userService.addUser();
}
//spring方式
@Test
public void demo02(){
String xmlPath = "com/scong/c_ioc_staticfacotry/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService)applicationContext.getBean("userService");
userService.addUser();
}
}
3. 实例工厂
实例工厂:工厂中提供的方法都是非静态的
修改工厂类:
public class MyBeanFactory {
public UserService createService(){
return new UserServiceImpl();
}
}
修改配置文件,先配置工厂实例,再配置userservice实例
<?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="myBeanFactory" class="com.scong.c_ioc_factory.MyBeanFactory"></bean>
<!-- 配置userservice
factory-bean 确定工厂实例
factory-method 确定普通方法
-->
<bean id="userService" factory-bean="myBeanFactory" factory-method="createService"></bean>
</beans>
测试:
public class TestFactory {
//手动创建方式
@Test
public void demo01(){
UserService userService = new MyBeanFactory().createService();
userService.addUser();
}
//spring方式
@Test
public void demo02(){
String xmlPath = "com/scong/c_ioc_factory/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService)applicationContext.getBean("userService");
userService.addUser();
}
}