5.Spring核心配置文件的相关配置

5.Spring核心配置文件的相关配置

 

5.1 bean

其实bean也是我们最熟悉的,每注册一个bean就是给spring的IOC容器中添加一个对象,在spring初始化的时候就已经帮我们创建好了,我们需要用的时候直接调用就行了。

几个重要的属性介绍:

  • id:bean的唯一标识符,也即是对象的变量名

  • class:属性定义Bean的类型,并使用完全限定的类名。

  • name:功能相当于取别名(这里的name可以取多个别名)下面就是取多个别名的例子

 <bean id="user" class="com.xuan.pojo.User" name="user3,user4,user5,user6,user7">
     <constructor-arg ref="student"></constructor-arg>
     <constructor-arg ref="teacher"></constructor-arg>
 </bean>
  • scope:bean的作用域

ScopeDescription
singleton (默认)为每个Spring IoC容器将单个bean定义的作用域限定为单个对象实例。
prototype Scopes a single bean definition to any number of object instances.
request 将单个bean定义的范围限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有一个在单个bean定义后面创建的bean实例。Only valid in the context of a web-aware Spring ApplicationContext.
session 将单个bean定义的范围限定为HTTP的生命周期SessionOnly valid in the context of a web-aware Spring ApplicationContext.
application 将单个bean定义的作用域限定为的生命周期ServletContext。Only valid in the context of a web-aware Spring ApplicationContext.
websocket 将单个bean定义的作用域限定为的生命周期WebSocket Only valid in the context of a web-aware Spring ApplicationContext.
  • singleton(单例):容器只创建一个对象

 

 

  • prototype(原型):每一次从容器get的时候都创建一个新的对象

 

 

 

 

 

5.2 alias(起别名)

怎么用?

  • 使用ApplicationContext的getBean方法里面传入别名或者本身的名字(bean指定的id属性)都是可以获取到制定的数据的。

 <alias name="user" alias="user2"></alias>

 

5.3 import(导入)

什么时候用?

  • 一般用于团队开发,多个配置文件通过导入的方式实现整合。

 <import resource="applicationContext.xml"></import>

 

 

 

posted @ 2020-07-16 21:45  xuan_study  阅读(477)  评论(0)    收藏  举报