Spring中的FactoryBean

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值