import 标签 导入其他的Bean配置文件
resource
:其他Bean配置文件名
bean 标签 管理对象
-
id
:对象名 -
class
: 对象的模板类(spring底层是通过反射实例化对象) -
name
: 起别名(可以起多个别名,多个别名之间用 逗号、空格或者“;”符号隔开。<s1、s2、s3、s4都可以访问>) -
autowire
: 自动装配 (有两种方式 byName<通过 id 属性> 和 byType<通过 class 属性>。使用 byType 的时候要注意注入的 bean 是唯一的,因为如果同时存在两个及以上的符合条件的 bean 时,他们的 id 名不同,class 属性相同,⾃动装载会抛出异常。) -
parent
: 当前bean 复制 IoC 容器中的其他bean 但是要当前 bean class 模板中要有 其他bean 模板的所有成员变量 -
depends-on
: 依赖关系 被依赖的 bean 优先创建 (Spring 作用域Scope 默认是单例singleton的,单例模式下当bean.xml 文件加载时,就会创建bean 对象。) -
scope
: bean作用域(默认是单例模式)
单例模式:当配置文件加载就会创建对象,并装在到 IoC 容器中。
原型模式:当通过上下文调用getBean(“配置文件Bean标签中的id”),才会去创建对象。
scope | |
---|---|
singleton | 单例,表示通过 IoC 容器获取的 bean 是唯一的 |
prototype | 原型,表示通过 IoC 容器获取的 bean 是不同的 |
request | 请求,表示在一次 HTTP 请求内有效 |
session | 会话,表示在一次用户会话内有效 |
… | … |
-
property 标签 使用无参构造和get、set方法创建对象
扫描二维码关注公众号,回复: 12882675 查看本文章name
: 成员变量名value
: 成员变量值(基本数据类型 和 String可以直接赋值,其他数据类型不能使用value,要使用ref)ref
: 将IoC中的另外一个Bean赋值给当前的成员变量 (DI 依赖注入)index
: 使用下标匹配
-
constructor-arg 标签 使用有参构造方式创建对象
(name、value、ref 和 index)和 property 标签中的一样
alias 标签 起别名
name
: 其他 bean的id名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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="Spring-AOP.xml"/>
<bean id="gogo" class="com.cl.pojo.Student" name="s1,s2 s3;s4" scope="singleton" autowire="byType">
<property name="id" value="1"/>
<property name="name" value="小号"/>
</bean>
<bean id="stu" class="com.cl.pojo.Student">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="小里"/>
<constructor-arg name="addresses" ref="address"/>
</bean>
<bean id="address" class="com.cl.pojo.Address">
<property name="id" value="1"></property>
<property name="address" value="迎风路"></property>
</bean>
<bean id="address01" class="com.cl.pojo.Address" parent="address"></bean>
<alias name="gogo" alias="student"/>
</beans>