不需要重复的“造轮子”,可以使用已经存在的轮子简化开发流程
早期为SSH框架,即:Struct2 + Spring + Hibernate
现在多数使用的是SSM框架,即:Spring MVC + Spring + Mybatis
目前Spring 的稳定版本为:5.3.0
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
一句话概括:
目前现代化的Java开发,都是基于Spring进行的
关于Spring boot的特性
在IOC诞生之前的业务编写流程举例:
UserDao数据库接口
UserDaoImpl实体类实现数据库接口方法
UserService业务接口
UserServiceImpl实体类实现业务接口方法
这样的结构乍一看没什么问题,但当用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码! 如果程序代码量十分大,修改一次的成本十分昂贵。
而我们在业务层使用一个针对Dao接口的set方法即可解决这个问题
//原来
private UserDao userDao = new UserDaolmpl();
//改进后
private UserDao userDao;
// 与方式1的本质区别:利用set进行动态实现值的注入!
// alt + insert 调出Generate
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
作出这样的改变后,我们可以发现,此时的Dao接口实体化类型的控制权已经从我们程序员手里转移到了用户的手里!
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建,系统的耦合性大大降低了,可以更加专注的再业务上的实现了。这是IOC的原型。
首先要创建POJO实体类
package com.xiafan;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
配置Spring的xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.xiafan.Hello">
<property name="str" value="HelloWorld"/>
bean>
beans>
测试使用
package com.xiafan;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void Test01(){
//获取Spring的上下文
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//用Spring创建的对象可以直接取出来用
Hello hello =(Hello) applicationContext.getBean("hello");
System.out.println(hello.getStr());
}
}
默认会使用无参构造方法创建对象
bean.xml中:
<bean id="user1" class="com.xiafan.pojo.User">
<property name="name" value="faker"/>
bean>
java代码中:
User user1 = (User) context.getBean("user1");
user1.showName();
若要实现有参构造,有三种方式(都是用bean中的构造器标签实现的)
方式一:通过参数下标传递构造方法参数
bean.xml中:
<bean id="user2" class="com.xiafan.pojo.User">
<constructor-arg index="0" value="the shy"/>
bean>
java代码中:
User user2 = (User) context.getBean("user2");
user2.showName();
方法二:通过参数类型传递构造方法参数(不建议使用,因为如果有两个参数类型相同,则因为只能赋一个值而无法顺利构造)
bean.xml中:
<bean id="user3" class="com.xiafan.pojo.User">
<constructor-arg type="java.lang.String" value="rookie"/>
bean>
java代码中:
User user3 = (User) context.getBean("user3");
user3.showName();
方法三:类似java语言创建对象时一样传递参数,即对应参数名直接传参
bean.xml中:
<bean id="user4" class="com.xiafan.pojo.User">
<constructor-arg type="java.lang.String" value="rookie"/>
bean>
java代码中:
User user4 = (User) context.getBean("user4");
user4.showName();
以上代码的运行结果为:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5imxg2gk-1633703901299)(C:\Users\利姆鲁\AppData\Roaming\Typora\typora-user-images\image-20210916223924401.png)]
注意到:
1.通过代码运行结果可以发现,我们所调用的所有对象,都是在beans.xml配置文件加载的时候就已经创建了的,而不是之后需要调用对象的时候再实时的创建,是一开始就全部创建了
2.创建对象的时候,使用的是单例模式
<alias name="user1" alias="yonghu1"/>
<bean id="user1" class="com.xiafan.pojo.User">
<property name="name" value="faker"/>
bean>
import一般用于团队开发使用,可以将其他配置文件整合到使用import标签的配置文件,测试或者实际调用的时候直接使用整合的配置文件即可。
<import resource="bean1.xml" />
<import resource="bean2.xml" />
<import resource="bean3.xml" />
依赖和注入是分开的。
所谓依赖:指的是bean对象的创建依赖于容器
所谓注入:指的是bean对象中的所有属性由容器进行注入
在IOC创建对象的部分已经讲过了,不再赘述
对于不同类型的数据使用不同的注入方式
<bean id="address" class="com.xiafan.pojo.Address">
<property name="address" value="广州"/>
bean>
<bean id="student" class="com.xiafan.pojo.Student">
<property name="name" value="letme"/>
<property name="address" ref="address"/>
<property name="books">
<array>
<value>龙珠value>
<value>火影value>
<value>海贼value>
<value>死神value>
array>
property>
<property name="hobbies">
<list>
<value>玩手机value>
<value>玩电脑value>
<value>玩switchvalue>
<value>玩X-BOXvalue>
<value>玩ipadvalue>
list>
property>
<property name="cards">
<map>
<entry key="校园卡" value="201929230163"/>
<entry key="身份证" value="440982199901463380"/>
map>
property>
<property name="games">
<set>
<value>lolvalue>
<value>ralolvalue>
<value>只狼value>
<value>codvalue>
<value>彩虹六号value>
set>
property>
<property name="wife">
<null/>
property>
<property name="info">
<props>
<prop key="drive">1prop>
<prop key="url">2prop>
<prop key="username">3prop>
<prop key="password">4prop>
props>
property>
bean>
首先要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
P命名空间注入:用于对属性property进行注入,对应set注入
<bean id="user1" class="com.xiafan.pojo.User" p:name="ale" p:age="16"/>
C命名空间注入:用于对构造函数的参数进行注入,对应构造器注入
<bean id="user2" class="com.xiafan.pojo.User" c:name="faker" c:age="18"/>
可以在bean标签中直接加入scope属性选择作用域
单例模式singleton(默认为单例模式)
单例模式即:在bean中以单例模式注册的对象在整个被引用的过程中,引用的是同一个对象,即该对象只创建一次
原型模式prototyer(需要手动改为原型模式)
原型模式即:在bean中以原型模式注册的对象每次被引用时会自动创建一个新的对象,这些对象都不是同一个对象,是不同的对象
request、session、application是在web开发中的作用域,在此处不再赘述,可以直接看Javaweb开发基础自行食用
byName:在xml配置文件上下文中查找,搜寻对象set方法后对应的值相同的bean的id,并对应赋值。(bean中的id要符合命名规则且id唯一,否则会报错)
public void setJiaCandy(JiaCandy jiaCandy) {
this.jiaCandy = jiaCandy;
}
public void setDrill(Drill drill) {
this.drill = drill;
}
<bean id="jiaCandy" class="com.xiafan.pojo.JiaCandy"/>
<bean id="drill" class="com.xiafan.pojo.Drill"/>
<bean id="person" class="com.xiafan.pojo.Person" autowire="byName">
<property name="name" value="rookie"/>
bean>
byType:在xml配置文件上下文中查找,搜寻与对象的类相同的bean的id,并对应赋值。(每种类只能有一个参数,否则会报错)
<bean id="jiaCandy" class="com.xiafan.pojo.JiaCandy"/>
<bean id="drill" class="com.xiafan.pojo.Drill"/>
<bean id="person" class="com.xiafan.pojo.Person" autowire="byType">
<property name="name" value="rookie"/>
bean>
使用注解实现自动装配**(重要)**
首先需要导入支持约束(在xml配置文件中):
<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">
再开启注解支持(在xml配置文件中):
<context:annotation-config/>
常用注解:
1.@Autowired:可在类中的引用属性上直接添加该注解,该注解默认先通过byType方式自动装配,若不符合再通过byName方式进行装配。
2.@Qualifier:用于配合@Autowired使用的注解,如果@Autowired通过byType和byName方式都无法找到工具bean,则可以使用该注解直接赋值bean的id来准确匹配工具bean。
有关的Java核心代码和beans.xml关键配置:
@Autowired
@Qualifier("jiaCandy")
private JiaCandy jiaCandy;
@Autowired
@Qualifier("drill")
private Drill drill;
<bean id="jiaCandy" class="com.xiafan.pojo.JiaCandy"/>
<bean id="drill" class="com.xiafan.pojo.Drill"/>
<bean id="person" class="com.xiafan.pojo.Person">
<property name="name" value="rookie"/>
bean>
3.@Nullable:标记属性可以为空,其作用和@Autowired(false)相同
4.@Resource:其作用相当于@Autowired和@Qualifier的组合,可以直接使用也可以给注解赋值使用;与@Autowired相反,@Resource默认先通过byName方式自动装配,若不符合再通过byType方式进行装配。
有关的Java核心代码和beans.xml关键配置:
@Resource(name = "jiaCandy")
private JiaCandy jiaCandy;
@Resource(name = "drill")
private Drill drill;
<bean id="jiaCandy" class="com.xiafan.pojo.JiaCandy"/>
<bean id="drill" class="com.xiafan.pojo.Drill"/>
<bean id="person" class="com.xiafan.pojo.Person">
<property name="name" value="rookie"/>
bean>
总结:@Autowired和@Qualifier的组合是目前spring的规范标准,比较推荐使用,而@Resource已被逐步替代
环境准备:
首先需要先导入aop依赖,在之前导入的包里面包含了aop依赖,这里不需要再导入
然后要在xml配置文件中添加扫描标签
<context:component-scan base-package="com.xiafan.pojo"/>
现在可以开始注解开发了
@Component:直接用在类上,起注册作用
//相当于
@Component
public class User {
private String name;
}
@Value:直接用在属性上,起注入作用
public class User {
//相当于
@Value("xiaohu")
private String name;
}
类似于@Component,在不同层的Java类中使用的注册注解有区别,作用一样,只因便于区分
dao层:@Repository
pojo层:@Component
service层:@Service
controller层:@Controller
@Scope:直接用在类上,表明该对象注册后的作用域
@Scope("singleton")//单例模式作用域
xml配置和注解的优缺点:
xml配置和注解的取舍:
了解AOP首先要了解代理模式。
代理模式分为静态代理和动态代理。
任何设计模式其实都是对为了解决现实中的问题而提出的:在这里的代理模式则对应于现实中的中介,买家和卖家之间不需要直接进行接触,即可通过中介完成一笔交易,这就是代理模式的思想。这样做可以使得客户端和真实角色的耦合性大大降低。
由四个角色组成:
静态代理模式的优缺点:
优点:
缺点:
为了解决静态代理模式的缺点,我们提出了动态代理模式
动态代理的核心是反射机制!
与静态代理相同,动态代理也由四个角色组成:
但动态代理的代理角色是动态引入的,而不是像静态代理一样写死在代码中的
动态代理分为两类:
JDK动态代理核心的两个类:Proxy类和InvocationHandler接口,查阅JDK文档进行了解
使用动态代理后,除解决静态代码的缺点和继承静态代码的优点外,还有更重要的优点:
什么是AOP
AOP(Aspect Oriented Programming)意为:**面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。**AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP在spring中所需了解的背景知识
springAOP可以提供声明式事务;允许用户自定义切面
以下名词需要了解下:
横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
目标(Target):被通知对象。
代理(Proxy):向目标对象应用通知之后创建的对象。
切入点(PointCut):切面通知 执行的 “地点”的定义。
连接点(JointPoint):与切入点匹配的执行点。
五种通知类:
AOP的意义
AOP的意义跟代理模式很相似:Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来,实现公共业务的重复利用,领域业务更纯粹 , 使得软件工程师可以更专注领域业务 , 其本质还是动态代理的思想。
spring中AOP的三种实现方式
方法一:让所需添加环绕的类实现spring自带的aop接口进行配置
<bean id="userService1" class="com.xiafan.service.UserServiceImpl"/>
<bean id="beforelog" class="com.xiafan.Log.BeforeLog"/>
<bean id="afterlog" class="com.xiafan.Log.AfterLog"/>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.xiafan.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="beforelog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
aop:config>
package com.xiafan.Log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class BeforeLog implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
//method : 要执行的目标对象的方法
//objects : 被调用的方法的参数
//Object : 目标对象
System.out.println(o.getClass().getName() + "调用了" + method.getName());
}
}
=====================================================================================================
package com.xiafan.Log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
//returnValue 返回值
//method被调用的方法
//args 被调用的方法的对象的参数
//target 被调用的目标对象
System.out.println(target.getClass().getName() + "调用了" + method.getName() + "结果返回值为" + returnValue);
}
}
方法二:使用AOP标签实现
<bean id="userService2" class="com.xiafan.service.UserServiceImpl"/>
<bean id="log" class="com.xiafan.Log.Log"/>
<aop:config>
<aop:aspect ref="log">
<aop:pointcut id="logpointcut" expression="execution(* com.xiafan.service.UserServiceImpl.*(..))"/>
<aop:before pointcut-ref="logpointcut" method="before"/>
<aop:after pointcut-ref="logpointcut" method="after"/>
aop:aspect>
aop:config>
package com.xiafan.Log;
public class Log {
public void before(){
System.out.println("我在前面before");
}
public void after(){
System.out.println("我在后面after");
}
}
方法三:使用注解实现
<aop:aspectj-autoproxy/>
package com.xiafan.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationLog {
@Before("execution(* com.xiafan.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("我是执行前啦");
}
@After("execution(* com.xiafan.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("我是执行后啦");
}
@Around("execution(* com.xiafan.service.UserServiceImpl.*(..))")
public void round(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tycHdRd1-1633703901306)(C:\Users\利姆鲁\AppData\Roaming\Typora\typora-user-images\image-20211002223532182.png)]
方式一:
把mybatis的核心配置文件中的数据源转移到spring配置文件中
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
bean>
在spring配置文件中配置sqlSessionFactory和sqlSession
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/xiafan/dao/*.xml"/>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
bean>
实现实体类
public class UserMapperImpl implements UserMapper{
//创建sqlsession对象
private SqlSessionTemplate sqlSession;
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> getUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUser();
}
}
在spring配置文件中配置dao实现类
<bean id="userMapperImpl" class="com.xiafan.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
bean>
此时的mybatis配置文件只需要配置setting和typeAliases即可
<configuration>
<typeAliases>
<package name="com.xiafan.pojo"/>
typeAliases>
configuration>
测试运行即可
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
List<User> user = userMapper.getUser();
for (User user1 : user) {
System.out.println(user1);
}
}
方式二:多数步骤和方式一相同,不同的地方在于实体类的实现
关键在于继承了SqlSessionDaoSupport类,该类实际上也就是帮我们封装了sqlsession的获取过程而已,完全可以自行编写工具类,但既然有现成的可以直接使用现成的。
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> getUser() {
return getSqlSession().getMapper(UserMapper.class).getUser();
}
}
spring的事务管理分为声明式事务和编程式事务。
编程式事务管理
声明式事务管理
编程式事务即以前使用的,使用try-catch-finally语句对需要进行事务操作的语句进行包含和操作即可,这里不再详说。
这里主要关注声明式事务如何使用的。
首先需要在spring配置文件头导入tx约束
配置事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
配置事务通知advice
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
配置aop,将事务通知织入业务中
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
aop:config>
补充:spring事务的七大传播特性
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!