Spring学习笔记
Spring配置
别名
1 | <!-- 别名,如果添加了别名,我们也可以使用别名获取到对象--> |
Bean的配置
1 | <!-- |
import
这个import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个。
DI依赖注入
构造器注入
Set方式注入【重点】
实体类属性
1 | private String name; |
xml配置
1 | <bean id="student" class="com.demospring.pojo.Student"> |
拓展方式注入
P命名空间注入
需要添加xml约束
xmlns:p="http://www.springframework.org/schema/p"
1 | <!-- p命名空间注入,可以直接注入属性的值:property--> |
C命名空间注入
需要添加xml约束
xmlns:c="http://www.springframework.org/schema/c"
1 | <!-- c命名空间注入,通过构造器注入:construct-args--> |
Bean的作用域
| Scope | Description |
|---|---|
| singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
| prototype | Scopes a single bean definition to any number of object instances. |
| request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. |
| session | Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. |
| application | Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext. |
| websocket | Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext. |
1.单例模式(Spring默认机制)
1 | <bean id="user" class="com.demospring.pojo.User" p:name="李四" p:age="23" scope="singleton"/> |
2.原型模式:每次从容器get的时候,都会产生一个新对象!
1 | <bean id="user1" class="com.demospring.pojo.User" c:name="王五" c:age="38" scope="prototype"/> |
3.其余的request,session,application这些只能在web开发中用到
Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显式的配置
- 在java中显式的配置
- 隐式的自动装配bean【重要】
ByName自动装配
1 | <bean id="people" class="com.demospring.pojo.People" autowire="byName"> |
autowire="byName"
ByName:会自动在容器上下文中查找,和自己对象set方法后面的值对象的beanid!
Bytype自动装配
1 | <bean id="people" class="com.demospring.pojo.People" autowire="byType"> |
autowire="byType"
ByType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
小结:
- byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一样
使用注解实现自动装配
1.导入约束:context约束
2.配置注解的支持:context:annotation-config/
1 |
|
@Autowired
直接在属性上使用即可!也可以在set方法上使用
1 |
|
使用Autowird我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC容器存在
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=”xxxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
使用注解开发
在Spring4之后,需要使用注解开发,必须要保证aop的包导入了

使用注解需要导入context约束,增加注解的支持
1 | <!-- 指定要扫描的包,这个包下的注解就会生效--> |
@Component:组件,放在类上,说明这个类被Spring管理了,就是Bean!
注入属性
1 | /** |
衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照MVC三成架构分层
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解的功能都是一样的,都是代表将某个类注册到Spring容器中装配
作用域
1 | ("prototype") |
使用Java的方式配置Spring
1 | package com.demospring.config; |
