一、初探Spring
Spring的优点
●Spring是一 个开源的免费的框架(容器)
●Spring是- 个轻量级的、非入侵式的框架
●控制反转(I0C) ,面向切面编程(AOP)
●支持事务的处理,对框架整合的支持
一句话: Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
二、IOC
1
通常,我们构建一个项目会有以下内容:
- UserDao接口
- UserDaolmpl实现类
- UserService业务接口
- UserServicelmpl业务实现类
而实际上用户调用的是业务层,dao层不需要用户操作
2
使用Spring来创建对象,这些都称为Bean
在配置文件加载的时候,容器中管理的对象就已经初始化了
3
ioc的思想是通过set动态实现值的注入
总的一句话:对象由Spring来创建、管理、装配!
<bean id="hello" class="com.lx.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值
<bean id="userService" class="com.lx.service.UserServiceImpl">
<property name="userDao" ref="mysqlImpl"/>
</bean>
ref 引用Spring容器中已经创建好的对象
value 具体的值,基本类型变量
<bean id="user" class="com.lx.pojo.User" name="user2 user3 u2 u3">
<constructor-arg type="java.lang.String" value="不学了"/>
</bean>
name可以同时取多个别名
三、依赖注入
3.1 构造器注入
用到的class就是构造器注入
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
通用:ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
3.2 set注入
依赖注入:set注入
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器注入
p命名空间与c命名空间
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入,可以直接注入属性的值;property -->
<bean id="user" class="com.lx.pojo.User" p:name="张三" p:age="18"/>
<!-- c命名空间注入,透过构造器注入;construct -->
<bean id="user2" class="com.lx.pojo.User" c:name="李四" c:age="20"/>
</beans>
四、Bean的自动装配
●byname的时候,需要保证所有bean的id唯一, 并且这 个bean需要和自动注入的属性的set方法的值一致!
●bytype的时候,需要保证所有bean的class唯一, 并且这个bean需要和自动注入的属性的类型-致!
<bean id="cat" class="com.lx.pojo.Cat"/>
<bean id="dog" class="com.lx.pojo.Dog"/>
<!--
byName: 会自动装配在容器上下文中查找,和自己对象set方法后面的值对应的 bean id
byType: 会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.lx.pojo.People" autowire="byName">
<property name="name" value="人干的事"/>
<!-- <property name="cat" ref="cat"/>-->
<!-- <property name="dog" ref="dog"/>-->
</bean>
注解自动装配
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="cat" class="com.lx.pojo.Cat"/>
<bean id="dog" class="com.lx.pojo.Dog"/>
<bean id="people" class="com.lx.pojo.People">
</bean>
</beans>
@Nullable
字段标记了这个注解,说明这个字段可以为null
如果显示定义了Autowired的required属性为false说明这个对象可以为null,否则不允许为空
@Autowired (required = false)
如果@Autowired自动装配的环境比较复杂,自动装配无法通过-一个注解[ @Autowired]完成的时候、我们可以
使用@Qulifier(value=“xx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
@Resource和@ Autowired的区别:
●都是用来自动装配的,都可以放在属性字段上
●@ Autowired通过byType的方式实现,而且必须要求这个对象存在! [常用]
●@Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况
下,就报错! [常用]
●执行顺序不同: @ Autowired通过byType的方式实现。@ Resource默认通过byname的方式实现。
五、注解
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定要扫描的包,在这个包下面的注解就会生效 -->
<context:component-scan base-package="com.lx.pojo"/>
<context:annotation-config/>
</beans>
@Component 组件,等价于<bean id=“xx” class=“com.lx.xx”
@Component
public class User {
public String name = "呵呵";
}
@Value(“xx”) 赋值,相当于
@Component
public class User {
@Value("xxx")
public String name;
}
衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
。dao [@Repository]
。service [@Service]
。controller [ @Controller]
。config [ @Configuration ]
这五个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
@Configuration 等价于beans.xml
@ComponentScan(“com.lx.pojo”) 扫描包
@Bean 类似bean标签
@Configuration
public class LxConfig {
//注册-个bean ,就相当 于我们之前写的一个bean 标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象!
}
}
六、AOP
6.1、代理模式
代理模式的好处:
●可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
●公共也就就交给代理角色!实现了业务的分工
●公共业务发生扩展的时候,方便集中管理
缺点:
●一个真实角色就会产生-个代理角色;代码量会翻倍开发效率会变低
6.1.1静态代理
类似中介,一般通过中介的setter来讲用户的实现类传入,另外增加方法。
6.1.2动态代理
●动态代理和静态代理角色- -样
●动态代理的代理类是动态生成的,不是我们直接写好的!
●动态代理分为两大类:基于接口的动态代理, 基于类的动态代理
。基于接口— JDK动态代理
。基于类: cglib
。java字节码实现: javasist
eg:
UserService.java
public interface UserService {
void add();
void delete();
void updata();
void query();
}
UserServiceImpl.java
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加一个用户!");
}
@Override
public void delete() {
System.out.println("删除一个用户!");
}
@Override
public void updata() {
System.out.println("修改一个用户!");
}
@Override
public void query() {
System.out.println("查询一个用户!");
}
}
ProxyInvocationHandler.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
//在这里要灵活运用反射的方法,来增加功能
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target,args);
return null;
}
public void log(String smg){
System.out.println("增加了一个"+smg+"方法");
}
}
Client.java
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//设置要代理的对象
pih.setTarget(userService);
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
6.2 AOP
●横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部
分,就是横切关注点。如日志,安全,缓存,事务等等…
●切面(ASPECT) :横切关注点被模块化的特殊对象。即,它是一个类。
●通知(Advice) :切面必须要完成的工作。即,它是类中的-一个方法。
●目标(Target) :被通知对象。
●代理(Proxy) :向目标对象应用通知之后创建的对象。
●切入点(PointCut) :切面通知执行的“地点”的定义。
●连接点(JointPoint) :与切入点匹配的执行点。
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="userService" class="com.lx.service.UserServiceImpl"/>
<bean id="log" class="com.lx.log.Log"/>
<bean id="afterlog" class="com.lx.log.AfterLog"/>
<!-- 配置aop : 需要导入aop的约束-->
<aop:config>
<!-- 切入点 : expression : 表达式
第一个 * :正常格式要加的,后面跟一个类
第二个* : 类里的方法
(..) ;表示不一样的参数
-->
<aop:pointcut id="pointcut" expression="execution(* com.lx.service.UserServiceImpl.*(..))"/>
<!-- 执行环绕增加 -->
<!-- 把 log 这个类切入到 pointcut 这个 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
AOP 实现方法:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="userService" class="com.lx.service.UserServiceImpl"/>
<bean id="log" class="com.lx.log.Log"/>
<bean id="afterlog" class="com.lx.log.AfterLog"/>
<!-- 方式一 :使用原生Spring API 接口 -->
<!-- 配置aop : 需要导入aop的约束-->
<aop:config>
<!-- 切入点 : expression : 表达式
第一个 * :正常格式要加的,后面跟一个类
第二个* : 类里的方法
(..) ;表示不一样的参数
-->
<aop:pointcut id="pointcut" expression="execution(* com.lx.service.UserServiceImpl.*(..))"/>
<!-- 执行环绕增加 -->
<!-- 把 log 这个类切入到 pointcut 这个 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
</aop:config>
<!-- 方式二 : 自定义类 -->
<bean id="diy" class="com.lx.diy.DiyPointCut"/>
<aop:config>
<!-- 自定义切面, ref:要引用的类 -->
<aop:aspect ref="diy">
<!-- 切入点 -->
<aop:pointcut id="point" expression="execution(* com.lx.service.UserServiceImpl.*(..))"/>
<!-- 通知 -->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
<!-- 方式三 -->
<bean id="annotationPointCut" class="com.lx.diy.AnnotationPointCut"/>
<!-- 开启项目支持 -->
<aop:aspectj-autoproxy/>
</beans>
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
package com.lx.diy;
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 AnnotationPointCut {
@Before("execution(* com.lx.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=========方法执行前========");
}
@After("execution(* com.lx.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=========方法执行后========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要处理切入的点
@Around("execution(* com.lx.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
七、整合mybatis
1、编写数据源配置
2、sqlSessionFactory sql缓存工厂
3、SqlSessionTemplate :就是我们使用的sqlSession
spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--DataSource 数据源 :使用Spring的数据源替换Mybatis的配置
我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="lx20001024"/>
</bean>
<!--sqlSessionFactory sql缓存工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定Mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/lx/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate :就是我们使用的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能构造器注入sqlSessionFactory,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
4、给接口加实现类
UserMapperImpl.java
public class UserMapperImpl implements UserMapper{
//我们的所有操作,都使用sqlSession来执行,在原来,现在都使用SqLSessionTemplate;
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
UserMapperImpl2.java
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
// SqlSession sqlSession = getSqlSession();
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// return mapper.selectUser();
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.lx.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
<bean id="userMapper2" class="com.lx.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试类Mytest.java
package com.lx;
import com.lx.mapper.UserMapper;
import com.lx.pojo.User;
import com.lx.utils.MybatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void test() throws IOException {
// SqlSession sqlSession = MybatisUtils.getSqlSession();
// UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
//
// List<User> userList = usermapper.selectUser();
// for (User user : userList) {
// System.out.println(user);
// }
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConText.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
八、增加事务
spring-dao.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource 数据源 :使用Spring的数据源替换Mybatis的配置
我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="lx20001024"/>
</bean>
<!--sqlSessionFactory sql缓存工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定Mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/lx/mapper/UserMapper.xml"/>
</bean>
<!-- SqlSessionTemplate :就是我们使用的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能构造器注入sqlSessionFactory,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 配置声明式事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 结合AOP实现事务的织入 -->
<!-- 配置事务的类 :-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 给那些方法配置事务 -->
<!-- 配置事务的传播特性:new propagation-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut id="txPoiontCut" expression="execution(* com.lx.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoiontCut"/>
</aop:config>
</beans>