Spring学习总结
一,Spring介绍
1.概念
- Spring是轻量级的开源的JavaEE框架
- Spring是可以解决企业开发应用开发的复杂性
- Spring有两个核心部分:IOC和AOP
- IOC:控制反转,把创建对象过程交给Spring进行管理
- AOP:面向切面,不修改源代码进行功能增强
- Spring特点:
- 方便结构,简化开发
- Aop编程支持
- 方便程序测试
- 方便和其他框架整合
2.下载路径
- https://repo.spring.io/artifactory/release/org/springframework/spring/
二,IOC容器
1.IOC概念和原理
-
什么是IOC?
- 称为控制反转,把对象的创建和对象之间的调用交给Spring进行管理,降低耦合度
-
IOC底层原理
-
XML解析,工厂模式,反射
-
过程:
配置XML文件
<bean id="dao" class="创建对象的路径"></bean>
创建对象
class UserDao {
public void add() {
.....
}
}
class UserFactory {
public static UserDao getDao() {
//1.获取XML解析
String classValue = class属性值;
//2.通过反射创建对象
Class clazz = Class.forName(classValue);
//3.返回获取的对象
return (UserDao)clazz.newInstance();
}
}
2.IOC接口
- IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
- Spring提供IOC容器实现两种方式:BeanFactory ,ApplicationContext
- BeanFactory:
- IOC容器最基本实现,是Spring内部使用的接口,不提供给开发人员使用
- 加载配置文件的时候不会创建对象,当调用(获取)对象的时候创建
- ApplicationContext:
- BeanFactory的子类,提供更多更强大的功能,一般由开发人员使用
- 加载配置文件时创建对象
- ApplicationContext实现类
- FileSystemXmlApplicationContext:根据系统文件路径
- FilePathXmlApplicationContext:根据类路径
3.IOC操作–Bean管理
(1) XML文件实现
-
1.基于XML创建对象
<bean id="唯一标识" class="类的全路径"></bean>
(1)在Spring配置文件中,使用bean标签,添加相应属性,就可创建对象
(2)创建对象时,默认调用无参构造方法创建对象
-
2.基于XML注入属性
1)使用set方法注入
//创建实体类
public class User {
private String name;
public void setName(String name) {
this.name = name;
}
}
//XML文件配置
<bean id = "user" class = "User类的全地址">
//此处的name必须和你实体类的属性名一样
<property name = "name" value = "siri"></property>
</bean>
----------------------------------------------------------------------------------------------------
(2)使用构造方法注入
//创建实体类
public class Book {
private String name;
private String id;
public Book(String name , String id) {
this.name = name;
this.id = id;
}
}
//XML文件配置
<bean id = "book" class = "com.test01.Spring5.bean.Book">
<constructor-arg name = "name" value="siri"></constructor-arg>
<constructor-arg name = "id" value = "110"></constructor-arg>
</bean>
-
3.注入外部Bean
(1)创建实体类
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void addUser () {
System.out.println("addUser......");
userDao.update();
}
}
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("dao update");
}
}
public interface UserDao {
public void update ();
}
(2)XML配置文件
<bean id="userService" class="com.test01.Spring5.service.UserService">
<property name="userDao" ref="userDaoImpl"></property>
</bean>
使用实体类注入,不要用接口
<bean id="userDaoImpl" class="com.test01.Spring5.dao.UserDaoImpl"></bean>
-
4.注入外部Bean
(1)创建实体类
public class Department {
private String dname;
public void setDname(String dname) {
this.dname = dname;
}
}
public class Employer {
private String ename;
private Department department;
public void setEname(String ename) {
this.ename = ename;
}
public void setDepartment(Department department) {
this.department = department;
}
}
(2)配置XML文件
<bean id="employer" class="com.test01.Spring5.bean.Employer">
<property name="ename" value="siri"></property>
<property name="department">
<bean id="department" class="com.test01.Spring5.bean.Department">
<property name="dname" value="安保"></property>
</bean>
</property>
</bean>
-
5.FactoryBean
普通bean:在配置文件中定义bean类型就是返回类型
FactoryBean:在配置文件中定义bean类型可以和返回类型不一样
(1)实体类
public class MyBean implements FactoryBean<Cources> {
public Cources getObject() throws Exception {
Cources cources = new Cources();
cources.setCname("111");
return cources;
}
public Class<?> getObjectType() {
return null;
}
}
//配置XML文件
<bean id="myBean" class="com.test02.Spring5.bean.MyBean"></bean>
-
6.Bean作用域
默认是单实例,可以通过Bean标签的属性(scope)设置
singleton:单实例,默认设置
加载配置文件的时候就会创建实例
prototype:多实例
调用getBean()方法创建实例
-
7.Bean声明周期
1.调用无参构造函数创建实例
2.调用setter方法注入属性
3.把bean实例传递给bean的后置处理器方法
4.调用初始化方法(手动配置)
5.把bean实例传递给bean的后置处理器方法
6.获取到创建的Bean实例对象
7.销毁(手动配置)
代码:
(1)XML配置文件:
<bean id="beanLife" class="com.test02.Spring5.bean.BeanLife"
init-method="initMethon" destroy-method="destyMethod">
<property name="name" value="siri"></property>
</bean>
注释:
init-method标签调用手动配置的方法初始化
destroy-method标签调用手动配置的方法销毁
(2)实体类:
public class BeanLife {
private String name;
public BeanLife() {
System.out.println("1.调用无参构造函数创建Bean实例");
}
public void setName(String name) {
this.name = name;
System.out.println("2.调用setter方法注入属性");
}
public void initMethon () {
System.out.println("3.调用初始化函数");
}
public void destyMethod () {
System.out.println("5.销毁");
}
}
测试类:
public void test02 () {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Test02Bean.xml");
BeanLife beanLife = context.getBean("beanLife",BeanLife.class);
System.out.println("4.获取创建的Bean实例对象");
//销毁需要手动销毁
context.close();
}
注意:
ApplicationContext对象不能调用close()方法
-
8.引入外部文件
案列:配置德鲁伊连接池
(1)创建properties文件
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user
jdbc.username=root
jdbc.password=123456
(2)在Spring配置文件中配置名称空间context
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
(3)引入外部文件和配置连接池
<!--引入外部文件配置连接池-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</bean>
(2)注解实现
-
1.什么是注解
- 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,,),简化XML配置
-
2.Spring针对Bean管理中创建对象提供的注解
- @Component,@Service,@Controller,@Repository
-
3.属性注入
-
1.@Autowired:根据属性类型进行自动装配
@Autowired
private Study02 study02;
-
2.@Qualifier:根据属性名称进行注入
@Autowired
@Qualifier (value = "study02Impl")
private Study02 study02;
-
3.@Resource:根据类型或名称注入
- @Resource :直接根据类型注入
- @Resource (name=“名称”) :根据名称注入
-
4.@Value:注入普通类型属性
-
4.纯注解
@Configuration //将此类设置为配置类
@ComponentScan (basePackages = "com.test03.Spring5") //开启组件扫描
public class SpringConfig {
...
}
//加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Study01 study01 = context.getBean("study01", Study01.class);
study01.put();
三,AOP
1.概念
- 什么是AOP?
- 面向切面编程(方面),利用AOP可以对业务逻辑的各个部分进行隔离,降低耦合度,提高程序的可重用性,提高开发的效率
- 通俗的说,就是不用修改源代码,就可以在主干功能里面添加新功能
2.底层原理
- 第一种:有接口情况,使用JDK动态代理
- 第二种:没有接口情况,CGLIB动态代理
3.JDK动态代理
-
1.调用newProxyInstance方法:返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序
- newProxyInstance (ClassLoader loader , 类<?>[] interfaces , InvocationHandler h)
- 第一个参数:类加载器
- 增强方法类的接口,可以有多个接口
- 实现InvocationHandler接口,创建动态代理的增强方法
-
JDK动态代理编码
//接口
public interface UserDao {
public int add (int a , int b);
public String update (String id);
}
//实现接口的增强类
public class UserDaoImpl implements UserDao {
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public String update(String id) {
return id;
}
}
//创建动态代理对象类
class UserDaoProxy implements InvocationHandler {
//有参构造传递
private Object obj;
public UserDaoProxy (Object obj) {
this.obj = obj;
}
//增强逻辑
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前
System.out.println("方法之前---"+method.getName()+":传递的参数"+ Arrays.toString(args));
//执行增强的方法
Object res = method.invoke(obj, args);
//方法之后
System.out.println("方法之后---"+obj);
return res;
}
}
/测试类
//创建接口实现类代理对象
Class[] interfaces = {UserDao.class};
UserDaoImpl userDao = new UserDaoImpl();
UserDao res = (UserDao) Proxy.newProxyInstance
(JDKProxy.class.getClassLoader(), interfaces,new UserDaoProxy(userDao));
int resurt = res.add(1, 2);
System.out.println("resurt:"+resurt);
4.AOP术语
-
1.连接点
- 类里面哪些方法可以被增强,这些方法可以被称为连接点
-
2.切入点
-
3.通知(增强)
-
4.切面
5.AspectJ
四,事务管理
声明式事务管理
-
基于注解
步骤:
1.配置名称空间context,tx
2.开启注解扫描
3.引入外部连接池
4.配置连接池
5.创建JdbcTemplate对象,注入dataSourse连接数据库
6.开启事务管理
7.开启事务注解
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--1.开启组件扫描-->
<context:component-scan base-package="com.Spring5.test05"></context:component-scan>
<!--2.引入外部连接池-->
<context:property-placeholder location="jdbc.properties" system-properties-mode="FALLBACK"></context:property-placeholder>
<!--3.配置德鲁伊连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="password" value="${password}"></property>
<property name="username" value="${username}"></property>
</bean>
<!--4.配置JdbcTempLate对象,注入dataSource-->
<!--创建JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--5.开启事务管理-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--6.开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
1.propagation:事务传播行为
REQUIRED:如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)
REQUIRES_NEW:不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
2.ioslation:事务隔离级别
脏读:一个事务读取到另一个未提交但更新的数据
幻读:一个事务读取到另一个事务已提交的insert数据
不可重复读:一个事务可以读取到另一个事务已提交且更新的数据
隔离级别 脏读 幻读 不可重复读 解释
READ_UNCOMMITTED 有 有 有 读取未提交数据
READ_COMMITTED 无 有 有 读取已提交数据
REPEATABLE_READ 无 有 无 可重复读
SERIALIZABLE 无 无 无 串行化
3.timeout:超时时间
事务必须在规定时间类进行提交,若超时则回滚
默认值为-1表示不超时,可设置以秒单位计算
4.readOnly:是否只读
false(默认):表示可以增删改查
true:表示只可查询
5.rollbackFor:回滚
设置出现哪些异常进行事务回滚
6.noRollbackFor:不回滚
设置出现哪些异常不进行事务回滚
-
纯注解
@Configuration//声明配置类
@ComponentScan(basePackages = "com.Spring5")//开启组件扫描
@EnableTransactionManagement//开启事务
@PropertySource("jdbc.properties")//引入外部文件
public class Config {
@Value("${jdbc.driverClassName}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource () {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
//创建JdbcTemplate对象
@Bean
public JdbcTemplate jdbcTemplate (DataSource dataSource) {
//到IOC容器中找到名称为dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager (DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)