Spring 创建bean的几种方式
在XML配置文件中,通过bean标签创建bean,然后再通过spring容器进行管理
创建xml配置文件定义bean
一、通过构造函数创建
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="User" class="com.example.springioc.User"/> 7 </beans>
创建bean类
1 public class User { 2 public void test(){ 3 System.out.println("我是bean"); 4 } 5 }
通过创建容器对象来读取配置文件,这部分代码与后面的代码一样。
ApplicationContext context = new ClassPathXmlApplicationContext("appContext.xml"); User user = (User) context.getBean("User"); user.test();
二、通过静态工厂创建
创建静态工厂
public class UserFactory { private static final User user = new User(); public static User getUser(){ return user; } }
创建工厂bean,这里的factory-method就是获取User的对象的静态方法
<?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="UserFactory" class="com.example.springioc.UserFactory" factory-method="getUser"/> </beans>
三、通过实例工厂创建
使用实例方法创建对象
1 public class UserFactory { 2 private static User user = new User(); 3 public User getUser(){ 4 return user; 5 } 6 }
XML创建工厂bean。然后调用工厂非静态方法创建新的bean
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="UserFactory" class="com.example.springioc.UserFactory" /> 7 <bean id="User" factory-bean="UserFactory" factory-method="getUser"></bean> 8 </beans>标签:创建,几种,bean,User,Spring,工厂,public,user From: https://www.cnblogs.com/pengshuai1014/p/16654008.html