Spring入门第二课:Spring配置Bean的细节

1.配置bean的作用域:

  通过配置scope属性可以bean的作用域,参数有 prototype、request、session、singleton。

    1)singleton为单例,IoC容器只会创建一个实例,并在IoC容器实例化的时候,bean就已经被创建了。

    2)property为每次实例bean的时候,都会实例化一个新的bean,IoC实例化的时候,bean不会被创建。bean在加载的时候才会创建

<bean id="baoma" class="com.myspring.level2.demo.Car" scope="prototype">

2.使用外部属性文件:

  想要使用外部文件,必须先引入context的命名空间,在添加的上<context:property-placeholder location="classpath:...">标签,location里写外部文件的路径。通过${属性名}就可以访问到该变量,比如在外部文件zpd.property里写入name=xxxxxxx;想要访问这个name,如下:

    <context:property-placeholder location="classpath:zpd.property"/>
    <bean id="baoma" class="com.myspring.level2.demo.Car" scope="prototype">
        <property name="name" value="${name}"></property>
        <property name="brand" value="BMW"></property>
    </bean>

3.SpEL:

  SpEL是Spring表达式语言,是一个支持运行时查询和操作对象图的强大的表达式语言。语法类似于EL:SpEL使用#{..}作为定界符,所有在大括号中的字符都将被认为是SpEL

SpEL为bean的属性进行 动态赋值 提供了便利。value=#{classid},引用其他对象的属性,支持正则,可以调用静态方法。

4.IoC容器的bean的生命周期:

  在bean中声明init-method、destory-method属性的方法。

<bean id="baoma" class="com.myspring.level2.demo.Car" init-method="init" destroy-method="destooy">

  实现BeanPostProcessor接口,来配置bean的后置处理器。postProcessBeforeInitialization(init-method之前被调用)\postProcessAfterInitialization(init-method之后被调用)

public class MyBeanPostProcess implements BeanPostProcessor
{
    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException
    {
        System.out.println("你好啊");
        return arg0;
    }
    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException
    {
        System.out.println("再见啦");
        return arg0;
    }

}

  在bean中实例化该bean:

<bean class="com.myspring.level2.demo.MyBeanPostProcess"></bean>

5.通过工厂方法配置Bean:

  通过静态工厂方法配置bean:   直接调用一个类的静态方法就可以返回bean的实例,bean属性factory-method。

  通过实例工厂方法配置bean:   通过实例工厂方法配置bean。

6.FactoryBean:

 略

猜你喜欢

转载自www.cnblogs.com/zpdMulti/p/596957458_qq8.html
今日推荐