zoukankan      html  css  js  c++  java
  • 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:

     略

  • 相关阅读:
    maven创建父子工程
    webservice之jersey简单实用
    EL表达式处理字符串
    oracle不等于1怎么查?
    day_07 搭建Tomcat服务器使用Servlet服务,后端接受前端请求过来的表单数据并使用
    Day_06 流程控制-循环结构-嵌套循环结构的原理解析
    Day05_流程控制02 循环结构
    day_5 流程控制 选择结构的两种常用语句的使用语法
    day_04 运算符详解
    day_03 变量的数据类型详解
  • 原文地址:https://www.cnblogs.com/zpdMulti/p/596957458_qq8.html
Copyright © 2011-2022 走看看