4. Spring 配置

空~2022年9月6日
  • Spring
大约 1 分钟

4. Spring 配置

1. 别名

alias 的 name 值与 bean 的 id 绑定,起别名后两个名字都可以获取到对象

<bean id="hello" class="pojo.Hello">
  <constructor-arg value="1"/>
  <constructor-arg value="HelloSpring"/>
</bean>
<!--别名-->
<alias name="hello" alias="helloNew"/>

2. Bean 配置

<!--
    id:bean标识符,相当于对象名称
    class:全类名
    name:别名 可以多个,可以以空格,逗号,或分号隔开
-->
<bean id="hello" class="pojo.Hello" name="h h1,h2;h3">
  <constructor-arg value="1"/>
  <constructor-arg value="HelloSpring"/>
</bean>

3. import

合并多个配置文件

  1. 导入时文件不允许重名
  2. 在合并配置文件时,可以通配符( * : 表示任意字符)

提示

主配置文件名称不能包含在通配符的范围内

<?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">
  <import resource="beans.xml"/>
  <import resource="beans2.xml"/>
  <import resource="beans3.xml"/>
</beans>

4. bean 的作用域

bean作用域 默认情况下,同一个容器 get 的对象为同一个(单例)

@Test
public void Test() {
    // 获取Spring的上下文对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // 读取bean对象
    Hello hello = (Hello) context.getBean("hello");
    Hello hello1 = (Hello) context.getBean("hello");
    System.out.println(hello == hello1);
}

bean作用域2

  • singleton

默认, 单例模式

<bean id="user" class="pojo.User" c:age="20" c:name="name" scope="singleton"/>
  • prototype

原型模式, 每次从容器中 get 时都会产生一个新对象

<bean id="user" class="pojo.User" c:age="20" c:name="name" scope="prototype"/>

相关信息

request, session, application, websocket 只会在 web 开发中使用.