spring笔记3 bean的自动装配:

2016年1月29日

9:37

 

spring笔记 bean的自动装配:

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<bean id=”car” class=”com.firefly.spring.beans.autowire.Car”
    p:name=”baoma” p:price=”300000”
></bean>
 
<bean id=”phone” class=”com.firefly.spring.beans.autowire.Phone”
p:name=”iphone” p:price=”4000”
></bean>
 
<bean id=”person” class=”com.firefly.spring.beans.autowire.Person”
    p:name=”test” p:car-ref=”car” p:phone-ref=”phone”
></bean>
 
<bean id=”person1” class=”com.firefly.spring.beans.autowire.Person”
    p:name=”test” autowire=”byName”
></bean>

    运用autowire方法进行自动装配,byName-根据名字进行自动装配,byType-根据类型进行自动装配(基本不用,因为容易冲突)

    实际上,自动装配这种方法我们很少会用到,总不如自己制定填充明了。

 

bean之间的关系:继承与依赖

 

 

1
2
3
4
5
6
7
8
9
10
11
<bean id=”sword” class=”com.firefly.spring.beans.relation.Sword”
    p:brand=”破败王者之刃” p:size=”100”
></bean>
 
<bean id=”person” class=”com.firefly.spring.beans.relation.Person”
    p:name=”akali” p:age=”18” abstract=”true”
></bean>
 
<bean id=”person1” class=”com.firefly.spring.beans.relation.Person”
    parent=”person” depends-on=”sword”
></bean>

    person1继承person,用abstract修饰了的bean不能被用于创建实例,与抽象类相似;person1依赖sword,如果sword不存在,虚拟机会抛出异常。

 

bean的作用域

 

1
2
3
<bean id=”person2” class=”com.firefly.spring.beans.relation.Person”
    parent=”person” scope=”prototype”
></bean>

    scope的默认值为singleton:它是单例的,在容器 初始化的时候创建bean实例,整个容器的生命周期中,它只会被创建一次。

                               prototype:原型,它在每次请求是都创建一个新的bean,并返回。

 

bean内引用外部配置文件

db.propertise的代码为:

1
2
3
4
user=root
password=root
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///test

bean引用外部文件的代码为:

1
2
3
4
5
6
7
8
<context:property-placeholder location=”classpath:db.propertise”/>
 
<bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource”>
    <property name=”user” value=”${user}”></property>
    <property name=”password” value=”${password}”></property>
    <property name=”driverClass” value=”${driverclass}”></property>
    <property name=”jdbcUrl” value=”${jdbcurl}”></property>
</bean>

因为有的配置,像上面例子中对数据库连接的配置那样的,在真正发布的时候需要进行修改,如果全都配置在bean中,你要从许多的bean中去寻找,显然是不方便的。所以用一个配置文件将它独立出来,以便于修改。

 

spring中的spel:

1
2
3
4
5
6
7
<bean id=”phone” class=”com.firefly.spring.beans.spel.Phone” p:price=”5500”></bean>
 
<bean id=”person” class=”com.firefly.spring.beans.spel.Person”
    p:name=”Tom”  p:statue=”#{phone.price>5000?’土豪’:’屌丝’}”
>
    <property name=”phone” value=”#{phone}”></property>
</bean>

spel是spring的一种特殊语法,与el表达式类似。

格式为:#{}  将内容写在大括号里,可以写运算符,可以用于bean之间的相互引用。

 

bean的生命周期,与以前action的生命周期相似

 

已使用 Microsoft OneNote 2016 创建。