Spring 配置文件部分详解

来源:互联网 发布:淘宝怎么装修店铺视频 编辑:程序博客网 时间:2024/06/05 00:43

<alias>:设置别名(可以设置多个别名)

<?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">        <!-- 当有ID的时候,name可以配置多个别名 如: name="h he hel hell".可以用空格,逗号,分号分割每个别名-->        <bean id="hello" class="com.et.bean.Hello">            <!-- 根据构造方法参数下标:参数下标从0开始 -->            <constructor-arg index="0" value="elliott"/>        </bean>        <!-- 设置别名 -->        <alias name="hello" alias="welcome"/></beans>
package com.et.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.et.bean.Hello;public class Test {    public static void main(String[] args) {        ApplicationContext act=new ClassPathXmlApplicationContext("beans.xml");        Hello hello=(Hello)act.getBean("welcome");        hello.show();    }}

输出结果:
hello,Elliott


<bean>的配置

<?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就是java对象,由spring容器来创建管理 -->        <!-- ID是bean的标识符,要唯一,如果没有配置ID,那么默认为标识符 -->        <!-- 如果配置了ID又配置了name那么name就是别名,分隔符可以是空格,逗号,分号 -->        <!-- class 是bean的全限定名=包名+类名 -->        <!-- 如果不配置ID和name那么可以根据applicationContext.getBean(Class)获取对象 -->        <bean id="h1" name="hello" class="com.et.bean.Hello">            <property name="name" value="Elliott"></property>        </bean></beans>


如果不配置ID和name那么可以根据applicationContext.getBean()获取对象

package com.et.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.et.bean.Hello;public class Test {    public static void main(String[] args) {        ApplicationContext act=new ClassPathXmlApplicationContext("beans.xml");        Hello hello=act.getBean(Hello.class);        hello.show();    }}

当配置文件有两个bean的时候,程序报错

<?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="h1" name="hello" class="com.et.bean.Hello">            <property name="name" value="Elliott"></property>        </bean>        <bean id="h2" class="com.et.bean.Hello">            <property name="name" value="Elliott"></property>        </bean></beans>

运行报错


<import>

项目过于庞大或者配置过多的时候,采用分模块的方法

<import resource="com/et/xxx.xml"/>

路径”/”形式存在:因为文件夹路径是以”/”形式存在