项目加载时将数据缓存到properties中

 
 
<bean name="student" class="test.learn.pojo.Student">
    <property name="name" value="${name}" ></property>
</bean>

    <bean name="studentFactory" class="test.learn.config.StudentFactory" ></bean>

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties"  ref="studentFactory"/>
    </bean>

    <bean id="studentIni" class="test.learn.config.StudentIni" init-method="init"></bean>
package test.learn.config;

import org.springframework.beans.factory.FactoryBean;

import java.util.Properties;

public class StudentFactory implements FactoryBean<Properties> {

    public Properties getObject() throws Exception {
        System.out.println("FactoryBean...");
       Properties properties=new Properties();
       properties.setProperty("name","yanfang");
        return properties;
    }

    public Class<?> getObjectType() {
        return null;
    }

    public boolean isSingleton() {
        return false;
    }


}
package test.learn.config;

import org.springframework.beans.factory.InitializingBean;

public class StudentIni implements InitializingBean {
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean....");
    }

    public void init(){
        System.out.println("init....");
    }
}


输出结果:

FactoryBean...
InitializingBean....
init....
yanfang


Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean。FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象。


1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用


2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖


3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值