Spring
Framework, that framework. It is an overall configuration for a particular application in the field application system and part of the design implementation. It is equivalent to let others help you do some basic work, it can handle the system a lot of details, but the general framework is mature and robust.
Spring Overview
Spring is the IOC (the DI) and AOP container frame
Excellent characteristics of Spring
① noninvasive : API based application development Spring objects may not be in dependence on the Spring
② DI : DI - Dependency Injection, Inversion of Control (IOC) to achieve the most classic.
③ Oriented Programming : Aspect Oriented Programming - AOP
④ container : Spring is a container because it contains life cycle management and application objects
⑤ assembly of : Spring implements a simple application uses a complex arrangement of components are combined into. You can use XML and Java annotations combination of these objects in the Spring.
⑥ stop : Based on the IOC and AOP can integrate open source frameworks and excellent third-party libraries of various enterprise applications (in fact SpringMVC Spring itself provides the presentation layer and the Spring JDBC persistence layer).
Spring Modules
IOC 和 IN
The IOC (Inversion of Control): inversion control
Reverse the direction of acquiring resources - changed by the container initiative of resources will push to the required components, developers do not need to know how to create a resource is a container object, only need to provide a way to receive resources. This behavior is also known as passive form of lookup.
The DI (the Dependency Injection): dependency injection
That assembly with some predefined manner (e.g.: setter method) receiving resource injection from the container.
Summary: IOC is a kind of reversal of thought control, and DI is a concrete realization of the IOC.
IOC container implemented in Spring
Import Spring Framework jar package
Create a profile, common file name: applicationContext.xml or beans.xml
- Spring has thought IOC, IOC thinking must be done based on the IOC container, while the IOC at the bottom of the container is essentially a object factory
1) In the prior example of reading by IOC container Bean, need first instantiated IOC container itself .
2) Spring provides two implementations IOC containers
① BeanFactory: basically IOC container infrastructure inside the Spring, Spring is for itself, is not available to developers to use.
② ApplicationContext: BeanFactory sub-interfaces, provides more advanced features. Spring for users, almost all occasions the use of the underlying ApplicationContext BeanFactory instead.
The main ApplicationContext implementation class
The ClassPathXmlApplicationContext : the XML format in the profile corresponding to the classpath
FileSystemXmlApplicationContext: the corresponding file system configuration files in XML format
Bean created at initialization of a single embodiment, can also be specified by the Bean arranged multi-instance is created.
ConfigurableApplicationContext
Is the sub-interface ApplicationContext, some extensions method comprising
refresh () and close () let ApplicationContext has a startup, shutdown, and the ability to refresh the context. So to close this interface ApplicationContext need new object to call close () method
WebApplicationContext
Prepared specifically for WEB application, which allows the completion of initialization with respect to the root path WEB
Obtaining from the IOC bean container, while specifying the bean recommended id values and types
// get the object by id and class type configured in the XML file the HelloWorld helloWorld = cxt.getBean ( "helloWorld", the HelloWorld. Class );
bean tag
bean tag: springIOC fitted into the bean container
bean tag attribute
id: uniquely identify objects (may not be written, if the value written in must be unique)
class: Full assembly of the bean class name
bean sub-label
property: assigned object attribute
name: attribute name
value: property value
constructor-arg: the assignment by the constructors
Assigns them the bean
1. setXxx the bean () Assignment Method
2. bean constructor assignment Note: If the constructor parameter types are compatible, assignment errors may happen.
<bean id="student" class="com.bean.Student01"> <property name="name" value="小明"></property> <constructor-arg name="age" value="18"></constructor-arg> </bean>
3. p namespace
<bean id="student" class="com.bean.Student01" p:name="小明" p:age="18"> </bean>
Property values may be used
1. literal
Basic data types and packaging class, String other types can take literal way of injection
If the literal contains special characters, you may be used <! [CDATA []]> wrapped up or escape character literals
2. null value
<property name= "bookName"> <null/> </property>
3. Give bean cascade property assignment
Modify the original property value will set the cascade properties, generally not used
4. External declared bean, refer to other bean: At this value has failed to meet the requirements to use the ref attribute
<bean id="school" class="com.bean.School"> <property name="stus" ref="stu"></property> </bean>
The internal bean
When the bean instance only a specific property to use, it can be declared as an internal bean. Declared directly in the internal bean <property> or <constructor-arg> element, the need to set any attribute name or id
Internal bean can not be used in any other place, that can not get inside the bean directly in the container
Injecting property is set bean
Array and List :
You need to specify <list> tag, it contains a number of elements in the tag. These tags can be specified by a simple constant value <value>, designated by the references to other Bean <ref>. Built bean specified by <bean>. Empty elements specified by <null />. Even other collections can be embedded.
List and define an array of the same, use the <list> element.
Java.util.Set configuration requires <set> tag, as defined in method List.
<bean id="shop" class="com.spring.bean.Shop" > <property name= "bookList"> <!-- 以bean的引用为值的List集合 --> <list> <ref bean= "book01"/> <ref bean= "book02"/> </list> </property> </bean >
Map
By <map> tag defined, <map> tag may be used a plurality of <entry> tag as a child. Each entry contains a key and a value.
Key must be defined in the <key> tag, and since the type of the key value is not limited, and can be freely specified <value>, <ref>, <bean> or <null /> elements thereof.
<bean id="cup" class="com.spring.bean.Cup"> <property name="bookMap"> <map> <entry key="book" value-ref="bookMap"></entry> <entry> <key> <value>bookKey01</value> </key> <ref bean="book01"/> </entry> </map> </property> </bean>
A collection of types of bean
The set of configuration bean extract to the outside, available to other bean references, reuse
<util:list id="schoolList"> <ref bean="stu"></ref> </util:list>
FactoryBean
If you need a programmer involved in the process of creation of the bean, use FactoryBean
Bean common bean plants with different target return is not a specified instance of the class, which is returned to the factory bean getObject object method returns.
Org.springframework.beans.factory.FactoryBean factory bean must implement the interface, and override three methods
<bean id="schoolFactory" class="com.factoryBeanImpl.SchoolFactory"> </bean>
scope of the bean
可以在<bean>元素的scope属性里设置bean的作用域,以决定这个bean是单实例的还是多实例的。
singleton,是所有bean的默认作用域。注意:工厂bean是通过isSingleton()方法设置是否单例的
当bean的作用域为单例时,Spring会在IOC容器对象创建时就创建bean的对象实例
而当bean的作用域为prototype时,IOC容器在获取bean的实例时创建bean的实例对象
bean的生命周期
在配置bean时,通过init-method和destroy-method 属性为bean指定初始化和销毁方法
Spring IOC容器对bean的生命周期进行管理的过程:
① 通过构造器或工厂方法创建bean实例
② 为bean的属性设置值和对其他bean的引用
③ 调用bean的初始化方法
④ bean可以使用了
⑤ 当容器关闭时,调用bean的销毁方法
<bean id="stu" class="com.bean.Student" init-method="init" destroy-method="destroy"> </bean>
bean的后置处理器
① bean后置处理器允许在调用初始化方法前后对bean进行额外的处理
② bean后置处理器对IOC容器里的所有bean实例逐一处理,而非单一实例。
③ bean后置处理器需要实现接口:org.springframework.beans.factory.config.BeanPostProcessor。
在初始化方法被调用前后,Spring将把每个bean实例分别传递给上述接口的以下两个方法:
●postProcessBeforeInitialization(Object bean, String beanId):初始化之前执行
●postProcessAfterInitialization(Object, String):初始化之后执行
注意
参数bean:IOC容器中创建的对象
参数beanId:IOC容器中创建对象的beanId
引用外部文件
将一部分信息提取到bean配置文件的外部,以properties格式的属性文件保存起来,同时在bean的配置文件中引用properties属性文件中的内容,从而实现一部分属性值在发生变化时仅修改properties属性文件即可。
1. 创建properties属性文件
jdbc.username=root
jdbc.password=12345
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
2. 引入context名称空间
3.指定properties属性文件的位置
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
classpath: 引入当前项目中类路径下的资源文件
classpath*: 引入所项目中类路径下的资源文件
4.从properties属性文件中引入属性值
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" p:username="${jdbc.username}" p:password="${jdbc.password}" p:driverClassName="${jdbc.driverClass}" p:url="${jdbc.url}"> </bean>
自动装配
手动装配:在XML配置文件中以value或ref的方式明确指定属性值都是手动装配。
自动装配:根据指定的装配规则,不需要明确指定,Spring容器会自动将匹配的属性值注入bean中。
注意:自动装配属性的数据类型,只能是[非字面量]值。[字面量]值不能自动装配。即基本数据类型(包装类)+String类型都不可自动装配
装配方式
- 根据类型自动装配:将类型匹配的bean作为属性注入到另一个bean中。当有多个与目标bean类型一致将报错
- 根据名称自动装配:必须将目标bean的名称和属性名设置的完全相同
- 通过构造器自动装配:当bean中存在多个构造器时,此种自动装配方式将会很复杂。不推荐使用。
基于xml,自动装配(不推荐)
在bean中添加autowire="byName|byType"
<bean id="student" class="com.springdemo.autowired.Student" autowire="byType"></bean>
byName:通过类中的属性名与bean中id(IOC容器中的id匹配)。
* 如果数值一致,匹配成功。 如果不一致,装配失败(不会报错,装配null值)
byType:通过类中的属性类型与bean中的class匹配
* 如果一致,匹配成功。
* 如果未找到匹配类型,装配失败(装配null值)
* 如果匹配到多个兼容类型(父子关系:装配失败,结果会报错)
基于注解,自动装配bean
需在XML文档中先添加扫描组件标签,指定需被装配bean的package
<context:component-scan base-package="com.bookStore" use-default-filters="true"></context:component-scan>
base-package:Spring容器会扫描这个基类包及其子包中的所有类。当需要扫描多个包时可以使用逗号分隔。
如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类
use-default-filters="true":默认组件扫描(扫描当前base-package下的包及其子包),false:不扫描...
通过子标签控制包含与排除
<context:include-filter>包含扫描,扫描指定匹配规则下的包及其子包
注意:通过将use-default-filters属性设置为false,禁用默认过滤器,然后扫描的就只是include-filter中的规则指定组件了
<context:exclude-filter>排除扫描,子节点表示要排除在外的目标类
注意:将use-default-filters属性设置为true或默认
过滤表达式,指定类型
类别 |
示例 |
说明 |
annotation |
com.XxxAnnotation |
过滤所有标注了XxxAnnotation的类。这个规则根据目标组件是否标注了指定类型的注解进行过滤。 |
assignable |
com.BaseXxx |
过滤所有BaseXxx类的子类。这个规则根据目标组件是否是指定类型的子类的方式进行过滤。 |
aspectj |
com.*Service+ |
所有类名是以Service结束的,或这样的类的子类。这个规则根据AspectJ表达式进行过滤。 |
regex |
com\.anno\.* |
所有com.anno包下的类。这个规则根据正则表达式匹配到的类名进行过滤。 |
custom |
com.XxxTypeFilter |
使用XxxTypeFilter类通过编码的方式自定义过滤规则。该类必须实现org.springframework.core.type.filter.TypeFilter接口 |
4个注解:
1) 普通组件:@Component
2) 表述层控制器组件:@Controller
3) 业务逻辑层组件:@Service
4) 持久化层组件:@Repository
组件命名规则
①默认情况:使用组件的简单类名首字母小写作为bean的id
②使用组件注解的value属性指定bean的id: @Component(value="指定id名")
自动装配bean中的属性
实现原理
在指定要扫描的包时,<context:component-scan> 元素会自动注册一个bean的后置处 理器:AutowiredAnnotationBeanPostProcessor的实例。该后置处理器可以自动装配标记 了@Autowired、@Resource或@Inject注解的属性。
@Autowired
注入方式:既不是set注入,也不是构造注入。本质:是通过反射注入。
自动装配规则
优先使用byType进行装配,如果能唯一匹配,则装配成功。
如果匹配到多个兼容类型的bean,再照byName方式匹配(进行唯一筛选)
如果通过byName唯一确定bean,则装配成功,否则装配失败。
构造器、普通字段(即使是非public)、一切具有参数的方法都可以使用@Autowired注解
若某一属性允许不被装配,可以设置@Autowired注解的required属性为 false
required:默认值是true,必须装配该bean
required值为false时,如果IOC容器中存在该bean,则装配。如果没有,则不装配。
@Autowired注解也可以应用在数组类型的属性上
@Autowired注解也可以应用在集合属性上,此时Spring读取该集合的类型信息,然后自动装配所有与之兼容的bean。
@Autowired注解用在java.util.Map上时,若该Map的键值为String,那么 Spring将自动装配与值类型兼容的bean作为值,并以bean的id值作为键。
@Qualifier
必要时,可以组合使用@Qualifier(value="userDaoMyBatisImpl")注解指定beanId名
Spring甚至允许在方法形参上标注@Qualifiter注解以指定注入bean的名称。