Spring bean的定义

spring bean 是一个被实例化,组装,并通过 Spring IoC(Inversion of Control) 容器所管理的对象。

Spring bean的生命周期

Bean的定义——(BeanDefinition)Bean的初始化——Bean的使用——Bean的销毁

Spring bean的装配方式

  • 隐式的bean扫描发现机制和自动装配
  • 在java中进行显示配置
  • 在XML中进行显示配置
<bean id="xxService" class="com.xx.service">
          <constructor-arg ref="xxMapper"/>
            <constructor-arg ref="yyMapper"/>
    </bean>

Spring 容器

是bean对象的集合,通过IoC也叫DI(dependency injection)将被spring管理的bean放到spring容器中。

Spring 切面的定义和使用

@Aspect定义切面类

@Aspect
public class Aspect{

}

通过@Before、@After、@Around、@AfterReturning、@AfterThrowing注解标识切面执行的方式。需要注意,切面的目标必须是spring容器管理的组件,一般切面目标都会加@Component之类的注解。

Spring JDBC

传统的spring基于xml配置jdbc数据源

<!-- 1.配置数据源 -->
<bean id="dataSource"
	class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<!-- 1.1.数据库驱动 -->
	<property name="driverClassName"
		value="com.mysql.jdbc.Driver"></property>
	<!-- 1.2.连接数据库的url -->
	<property name="url"
		value="jdbc:mysql://localhost:3306/数据库名称?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true"></property>
	<!-- 1.3.连接数据库的用户名 -->
	<property name="username" value="root"></property>
	<!-- 1.4.连接数据库的密码 -->
	<property name="password" value="12345678"></property>
</bean>

<!-- 2配置JDBC模板 -->
<bean id="jdbcTemplate"
	class="org.springframework.jdbc.core.JdbcTemplate">
	<!-- 默认必须使用数据源 -->
	<property name="dataSource" ref="dataSource"></property>
</bean>

springboot使用yaml配置

spring:
  datasource:
  	# 连接池类型
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    # jdbc连接url
    url: jdbc:mysql://localhost:3306/数据库名称?characterEncoding=UTF-8
    username: 用户名
    password: 密码

Spring ORM

对象关系映射(Object Relational Mapping),简单来说就是数据表和面向对象编程语言中具体类的一种对应关系。常用的ORM框架有Jpa,Mybatis等,通过spring可以快速整合ORM框架。