配置javaBean

bean基本配置:

<bean id="exampleBean" class="examples.ExampleBean"></bean>

上述代码相当于java代码

  ExampleBean exampleBean=new ExampleBean();

id属性是bean的一种标识,通常被用来bean的引用

class是必须的属性,表示bean的源

 

为bean起别名 alias标签

增强可读性,在不同模块中使用

<bean id="student" class="com.Model.Student" destroy-method="close">
        
        <property name="username" value="admin"></property>
        <property name="password" value="admin"></property>
        <property name="children" value="false"></property>
        <property name="source" value="96"></property>
        <property name="school" ref="school"></property>
        <property name="likeTeacher">
            <bean class="com.Model.Teacher">
                <constructor-arg value="江老师"></constructor-arg>
                <constructor-arg value="京大附中"></constructor-arg>
            </bean>
        </property>
    </bean>
    <alias name="student" alias="admin"/>
public  void studentTest(){
        XmlBeanFactory factory=new XmlBeanFactory(
                new ClassPathResource("com/test/applicationContext.xml"));
        Student s=(Student) factory.getBean("admin");
        System.out.println(s.getUsername()+"\t"+s.getPassword()+"\t"+s.getSchool().getSchoolName()+"\t"+s.getLikeTeacher().getTeacherName());
        factory.destroySingletons();
    }

 

延迟加载lazy-init属性

默认启动spring容器自动初始化所有的bean,可以设置延迟加载

lazy-init=true开启懒加载,默认为false

<bean  lazy-init="true" id="school" class="com.Model.School">
        <constructor-arg>
            <value>京大附中</value>
        </constructor-arg>
    </bean>
View Code

 

工厂模式factory-method

cat.java:

Cat.java

CatFactory.java:

View Code

Test:

public class CatFactory {
    static Cat cat=new Cat("小辉",12); public Cat getCat(){ return cat; } }

 

如果一个Bean不能被new直接实例化,而是通过工厂类的某个方法创建的,需要把bean的class属性配置称为工厂类(或者把factory-bean属性配置称为工厂对象),factory-method属性配置为产生实例的方法。

<bean id="cat" class="com.Model.CatFactory" factory-method="getCat"></bean>

使用这种方式的话factory中的getCat方法必须是static,否则报错

<bean id="catFactory" class="com.Model.CatFactory"></bean>
<bean id="cat" factory-bean="catFactory" factory-method="getCat"></bean>

使用这种方式的话factory中的getCat方法不能是static修饰的,否则报错

 

构造函数<constructor-arg>

初始化Beans的时候,spring容器会自动初始化,bean的自动初始化一般是调用空的构造方法。如果构造方法是有参数的,怎么选择呢?

系统根据你的bean下面的参数的情况下自动选定构造方法,根据参数的类型,数量等等。对应的参数为先后顺序,与构造方法顺序相同。使用<constructor-arg>配置

    <bean id="dog" class="com.Model.Dog" >
        <constructor-arg index="0" value="阿旺"></constructor-arg>
        <constructor-arg index="1" value="5"></constructor-arg>
    </bean>
    <bean id="catFactory" class="com.Model.CatFactory">
        <constructor-arg name="dog" ref="dog"></constructor-arg>
    </bean>

index:指定参数的位置

value:指定参数的内容

ref:将参数的内容引用其他bean对象 ref有三个属性: bean 引用其他bean,没有限制 local只能引用本配置文件的bean  parent只能引用副配置文件中的bean

 

单态模式singleton(单例模式)

单态模式也称为单例模式,就是程序中只能存在一个实例。Spring默认为单态模式,如果想更改称为非单态模式(称为Prototype模式),需要把singleton属性设置称为false:

默认情况下使用spring创建对象是单例模式,这种方式创建独享非常容易出现安全性问题。使用bean标签的scope属性解决该问题。

    * singleton:默认的方式,单例,属性共享(一般情况下应当将数据放到方法的变量中)

    * prototype:多例,当一个bean是多例模式的情况下,lazy-init为false或者default无效,也就是说懒加载强制开启。

<bean id="exampleBean" class="examples.ExampleBean" singleton="false" />

 

配置属性

前面只是指定的构造方法的赋值,在bean中往往需要我们给它注入一些属性。

 

使用<property>标签为一般属性赋值,普通类型:String、int、double

    <bean id="student" class="com.Model.Student" destroy-method="close">
        
        <property name="username" value="admin"></property>
        <property name="password" value="admin"></property>
        <property name="children" value="false"></property>
        <property name="source" value="96"></property>
    </bean>

destory-method属性配置关闭方法,在丢弃java对象时会调用一次这个方法。

init-method初始化方法也可以加入

 注意:为属性赋值null要使用<null>标签,使用value子标签

<property name="password">
    <value><null /></value>
</property>

如果

<value></value>

赋值的是"",而不是null

 

赋值对象属性

在<property>中使用ref属性:

Spring配置文件中的Bean可以相互引用,引用时使用<ref>标签配合Bean的id属性。

<ref>可以应用在<construct-arg>构造函数参数中,也可以用在bean的property属性中

<property name="school" ref="school"></property>

除了使用ref引用其他的bean,还可以使用内部配置,类似于java中的内部类。

        <property name="likeTeacher">
            <bean class="com.Model.Teacher">
                <constructor-arg value="江老师"></constructor-arg>
                <constructor-arg value="京大附中"></constructor-arg>
            </bean>
        </property>

 

配置List、Set、Map、Properties属性

<property name="hobby">
            <list>
                <value>踢球</value>
                <value>游泳</value>
            </list>
        </property>
        <property name="sp">
            <set>
                <value>1</value>
                <ref bean="school" />
            </set>
        </property>
        <property name="mp">
            <map>
                <entry>
                    <key><value>游戏角色:</value></key> <!-- key -->
                    <value>狂战士</value> <!-- value -->
                </entry>
                <entry>
                    <key><value>HP:</value></key>
                    <value>3000</value>
                </entry>
                <entry>
                    <key><value>学校:</value></key> <!-- key -->
                    <ref bean="school"></ref> <!-- value -->
                </entry>                
            </map>
        </property>
        <property name="pro">
            <props>
                <prop key="url">江西生物科技职业学院</prop>
                <prop key="emial">1580909730@qq.com</prop>
            </props>
        </property>

如果是普通属性如String、Integer、Double、Boolean等,直接使用字符串即可

对象类型使用ref引用

有顺序的会按照先后顺序排序

使用代码示例:

public void TestLazy(){
        ApplicationContext contxt=new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
        Student s=(Student) contxt.getBean("admin");
        System.out.println(s.getHobby().get(0)+s.getHobby().get(1));
        Iterator it=s.getSp().iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        Map<String,?> mp=s.getMp();
        Set<String> ks=mp.keySet();
        Iterator ii=ks.iterator();
        while(ii.hasNext()){
            String key=(String) ii.next();
            System.out.println(key+"\t"+mp.get(key));
        }
        Properties pro=s.getPro();
        Enumeration p =pro.keys();
        while(p.hasMoreElements()){
            String s3=(String) p.nextElement();
            System.out.println(s3+": "+pro.getProperty(s3));
        }
        
    }
View Code

 

<idref>与<ref>的区别

<idref>与<ref>的作用都是配置java对象。<idref>的用法和<ref>基本相同,不同的是<idref>只有bean和local属性,没有parent属性。

<idref local="dataSource" />

Spring检查XML配置文件时,会检查<idref>配置的Bean存在不存在。而<ref>只有在第一次调用才会检查。

 

bena的destory-method设置销毁方法

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destory-method="close">
....
</bean>
   

bean的初始化方法init-method

<bean id="c" class="examples.C" init-method="init"></bean>

 

depends-on依赖对象

Spring会按照配置文件里Bean配置的先后顺序实例化Bean。但有时候在实例化A之前需要先实例化后面的B对象。这时可以使用depends-on,强制先B对象。例如:

<bean id="a" class="exampless.A" depends-on="b"></bean>

<bean id="b" class="examples.B"></bean>
这时会在实例化A对象的时候先检查B是否存在,如不存在则先实例化B对象。

 

属性自动装配autowire

如果每个属性都使用<ref>设置,一个大项目的Spring配置文件会十分庞大,为此Spring提供了自动装配机制,不用配置<ref>而根据某种规则自动配置属性

通过bean的autowire属性配置

<bean id="d" class="examples.D" autowire="byType" ></bean>

autowire的取值范围

autowire属性定义的莪不是需要自动装配的属性名,而是自动装配的原则。一旦装配,所有的属性都将遵循autowire定义的规则。

如果显式定义了<property>或者<constructor-arg>,会覆盖默认装配。(覆盖装配指的是优先级的。autowire<constructor-arg<property)

自动装配一般与依赖检查连用。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           ">
    <bean id="cat" class="com.Model.Cat">
        <property name="name"><value>喵咪</value></property>
        <property name="age"><value>3</value></property>
    </bean>
    <bean id="dog" class="com.Model.Dog"></bean>
    <bean id="school" class="com.Model.School">
        <constructor-arg index="0">
            <value>江西生物科技职业学院</value>
        </constructor-arg>
    </bean>
    <bean id="home" class="com.Model.Home" autowire="byType">
        <property name="address">
            <value>青山湖大道</value>
        </property>
        <property name="schoolList">
            <list>
                <bean class="com.Model.School"></bean>
                <ref bean="school"/>
            </list>
        </property>
    </bean>
    <alias name="home" alias="家"/>
   
</beans>
View Code
package com.test;

import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.Model.Dog;
import com.Model.Home;

public class TestHome {
    @Test
    public void TestAutoWire(){
        XmlBeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/test/applicationContext.xml"));
        Home home=(Home) factory.getBean("家");
        System.out.println(home.getCat().getName()+"\t"+home.getAddress()+"\t"+home.getSchoolList().get(0).toString()+"\t"+home.getSchoolList().get(1).toString());
        Dog dog=home.getDog();
        Dog dog1=home.getDog1();
        String message=(dog==dog1)?"是同一只狗":"不是同一只狗";
        System.out.println("dog和dog1"+message);
    }

}
View Code

 

 

依赖检查dependency(这个属性在spring3的时候被取消了)

有些时候某些Bean的属性配置有错误,比如某个属性没有设置。这种错误在程序启动的时候不会有任何异常表现,会一直潜伏到Spring调用该Bean才被发现。为了防止这种情况,Spring提供依赖检查,在程序启动的时候检车依赖配置。如果有错误,启动的时候就会抛出异常,以便发现配置错误。

通过<bean>的dependency-check设置依赖检查规则,例如:

<bean id="bean" class="examples.Bean" dependency-check="all"></bean>

dependency的属性取值范围

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值