1.通过FactoryBean工厂模式创建出bean实例
1.1 FactoryBean接口中定义的getObject方法调用bean中的空构造方法创建bean实例对象;
1.2 FactoryBean接口中的定义的getObjectType方法获取bean的类型;
1.3 FactoryBean接口中的定义的isSingleton方法定义bean为单例模式,默认为true;
2.通过bean的set方法注入属性的值和引用
3.通过init方法初始化bean
4.bean可以被使用了
5.通过destroy方法销毁bean
整体流程:
测试代码
bean部分
-----------------------------------------------------------------
@AllArgsConstructor
@Data
public class User{
private int id;
private String username;
private String password;
public User() {
System.out.println("第一步:通过空构造创建bean");
}
public void setUsername(String username) {
System.out.println("第二步:执行set方法");
this.username = username;
}
public void initMethod(){
System.out.println("第三步:执行初始化方法");
}
public void destroyMethod(){
System.out.println("第五步:执行销毁方法");
}
@Override
public String toString() {
return "第四步:使用bean实例";
}
}
测试部分
------------------------------------------------------------------
public class MyTest {
@Test
public void testMethod(){
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext("pojo.xml");
//获取实例
Object user = context.getBean("user");
//使用实例
System.out.println(user.toString());
//当关闭容器时会调用destroy销毁bean
context.close();
}
xml配置部分
------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="user" class="com.whxh.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
<property name="username" value="第二步:bean属性的设置(调用set方法)和外部bean的注入">
</property>
</bean>
</beans>