Spring
笔记参考:https://blog.youkuaiyun.com/qq_41286666/article/details/123786690
优点
- Spring是一个开源的免费框架
- Spring是一个轻量级、非入侵式的框架
- 控制反转(IOC),面向切面(AOP)
- 支持事务处理,对框架整合支持
总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
控制: 谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的
反转: 程序本身不创建对象,而变成被动的接收对象。
HelloSpring
引入配置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
装配bean
<bean id="person" class="com.tintin.entry.Person">
<property name="str" value="spring"/>
</bean>
获取容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
IOC创建对象方式&配置
- 使用无参构造创建对象(默认)
<bean id="person" class="com.tintin.entry.Person">
<property name="str" value="spring"/>
</bean>
<!-- 取别名1 -->
<alias name="person" alias="newPersonName"/>
<!-- 取别名2 -->
<bean id="person" class="com.tintin.entry.Person" name="person2 person3 ...">
<constructor-arg name="str" value="stringName"/>
</bean>
-
使用有参构造
方法一:下表赋值
<bean id="person" class="com.tintin.entry.Person"> <constructor-arg index="0" value="constructor-0"/> </bean>
方法二:类型
<bean id="person" class="com.tintin.entry.Person"> <constructor-arg type="java.lang.String" value="stringValue"/> </bean>
方法三:参数名
<bean id="person" class="com.tintin.entry.Person"> <constructor-arg name="str" value="stringName"/> </bean>
-
applicatin.properties
<import resource="bean.xml"/> <import resource="bean2.xml"/> <import resource="bean3.xml"/>
依赖注入(三种方法)
- 依赖注入简单来说就是给类中的属性赋值。
1、构造器注入
参考:IOC创建对象方式&配置
2、SET注入
<?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">
<bean id="address" class="com.tintin.entry.Address" c:address="广东省广州市"/>
<bean id="student" class="com.tintin.entry.Student">
<!-- 第一种注入:普通值注入,value-->
<property name="name" value="张三"/>
<!-- 第二种注入:bean注入,ref-->
<property name="address" ref="address" />
<!-- 第三种注入:数组的注入-->
<property name="books">
<array>
<value>book1</value>
<value>book2</value>
<value>book3</value>
</array>
</property>
<!-- list注入-->
<property name="hobbys">
<list>
<value>hobbys1</value>
<value>hobbys2</value>
<value>hobbys3</value>
</list>
</property>
<!-- Map注入-->
<property name="card">
<map>
<entry key="key1" value="value1"/>
<entry key="key2" value="value2"/>
</map>
</property>
<!-- Set注入-->
<property name="games">
<set>
<value>set1</value>
<value>set2</value>
</set>
</property>
<!-- Properties注入-->
<property name="info">
<props>
<prop key="propertyKey1">propertyValue1</prop>
<prop key="propertyKey2">propertyValue2</prop>
</props>
</property>
<!-- null注入-->
<property name="wife">
<null></null>
</property>
</bean>
</beans>
3、p命令空间赋值
<?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">
<bean id="person" class="com.tintin.entry.Person" p:str="p标签赋值" />
<bean id="person" class="com.tintin.entry.Person" c:str="c标签赋值" />
</beans>
事务
开启事务支持
<?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/>
</beans>
注解开发
JAVA方式配置
@Configuration
@ComponentScan("com.kuang.pojo") //扫描包
@Import(MyConfig2.class)
public class MyConfig {
//注册一个bean,就相当于之前写的bean标签。
//方法的名字,相当于bean标签的id属性。
//方法的返回值,相当于bean标签的class属性。
@Bean
public User getUser(){
return new User(); //返回要注入bean的对象
}
}
代理模式
(代理的是接口)
角色分析:
- 抽象角色:一般会使用接口或者抽象类解决。
- 真实角色:被代理的角色。
- 代理角色:代理真实角色,一般会做一些附属操作。
- 客户:访问代理对象的人。
要求:真实角色和代理角色都要实现同一个接口。
静态代理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I2fu9Idt-1669000718682)(/Users/tintin/Library/Application Support/typora-user-images/image-20221111194411542.png)]
UserService.java
public interface UserService {
public void add();
public void select();
}
UserServiceImpl.java
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("UserServiceImpl-add");
}
@Override
public void select() {
System.out.println("UserServiceImpl-select");
}
}
Proxy.java
public class Proxy implements UserService {
UserServiceImpl userService;
public Proxy(UserServiceImpl userService) {
this.userService = userService;
}
@Override
public void add() {
log("add");
userService.add();
}
@Override
public void select() {
log("select");
userService.select();
}
public void log(String method){
System.out.println("log:" + method );
}
}
Client.java
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
Proxy proxy = new Proxy(userService);
proxy.add();
}
}
代理模式等好处
- 可以使角色操作更加存粹,不用去关注一些公共的业务
- 公共的业务交给代理觉得,实现了业务的分工
- 公共业务发生扩展时候,方便集中管理
缺点
- 一个真实角色就会产生一个代理角色,代码量会增加,开发效率会变低
动态代理
- 动态代理和静态代理角色一样
- 动态代理是动态生成的,不是直接写好的
- 动态代理分类:基于接口的动态代理、基于类的动态代理
- 基于接口——JDK动态代理
- 基于类——cglib
- java字节码实现——javasist
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iLejVDR8-1669000718683)(/Users/tintin/Library/Application Support/typora-user-images/image-20221111201746015.png)]
//UserService
public interface UserService {
public void add();
public void select();
}
//UserServiceImpl
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("UserServiceImpl-add");
}
@Override
public void select() {
System.out.println("UserServiceImpl-select");
}
}
//ProxyInvocationHandler
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 {
Object invoke = method.invoke(target, args);
return invoke;
}
}
//Client
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
ProxyInvocationHandler proxyIn..ionHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setTarget(userService);
UserService proxy = (UserService) proxyInvocationHandler.getProxy();
proxy.add();
}
}
AOP
公共部分
UserServiceImpl.java
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("add");
}
@Override
public void delete() {
System.out.println("delete");
}
}
UserService.java
public interface UserService {
public void add();
public void delete();
}
Client
public class Client {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
方式一:使用原生的api接口
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"
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.tintin.service.UserServiceImpl"/>
<bean id="afterLog" class="com.tintin.log.AfterLog"/>
<bean id="logBefore" class="com.tintin.log.LogBefore"/>
<!--方式一:使用原生的api接口-->
<!--导入aop-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的位置,* * * *)返回类型/包名/方法/参数-->
<aop:pointcut id="poincut" expression="execution(* com.tintin.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="afterLog" pointcut-ref="poincut"/>
<aop:advisor advice-ref="logBefore" pointcut-ref="poincut"/>
</aop:config>
</beans>
方法二:自定义类实现AOP 【主要是切面定义】
public class MyPointCut {
public void before(){
System.out.println("-------before-------");
}
public void after(){
System.out.println("-------after-------");
}
}
<?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 id="mypointcut" class="com.tintin.log2.MyPointCut"/>
<!-- 方式二:自定义类 -->
<aop:config>
<!-- 自定义切面,ref为要引入的切点 -->
<aop:aspect ref="mypointcut">
<!-- 切入点 -->
<aop:pointcut id="point" expression="execution(* com.tintin.service.UserServiceImpl.*(..))"/>
<!-- 通知 -->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
方法三:
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.tintin.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---before---");
}
@After("execution(* com.tintin.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---after---");
}
}
<?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 id="annotationPointCut" class="com.tintin.log3.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy />
</beans>
整合MyBatis
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pWmS0Za5-1669000718683)(/Users/tintin/Library/Application Support/typora-user-images/image-20221112210858174.png)]
方法一:
myBatisConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--别名-->
<typeAliases>
<package name="com.tintin.entry"/>
</typeAliases>
</configuration>
springConfig.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:context="http://www.springframework.org/schema/context"
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/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据原-->
<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="12345678"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFatory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatisConfig.xml"/>
<property name="mapperLocations" value="classpath:com/tintin/mapper/*.xml"/>
</bean>
<!--sqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFatory"/>
</bean>
</beans>
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"
xmlns:context="http://www.springframework.org/schema/context"
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/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="springConfig.xml"/>
<bean id="UserMapper" class="com.tintin.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="userMapper2" class="com.tintin.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFatory"/>
</bean>
</beans>
UserMapperImpl.java
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> listUser() {
return sqlSessionTemplate.getMapper(UserMapper.class).listUser();
}
}
main.java
public static void main(String[] args) {
ClassP...Context classP...Context = new ClassP...Context("applicationContext.xml");
//方法一:
UserMapper userMapper = (UserMapper) classP...Context.getBean("userMapper");
List<User> userList = userMapper.listUser();
for (User user : userList) {
System.out.println(user);
}
}
方法二:SqlSessionDaoSupport
myBatisConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--别名-->
<typeAliases>
<package name="com.tintin.entry"/>
</typeAliases>
</configuration>
springConfig.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:context="http://www.springframework.org/schema/context"
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/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据原-->
<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="12345678"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFatory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatisConfig.xml"/>
<property name="mapperLocations" value="classpath:com/tintin/mapper/*.xml"/>
</bean>
</beans>
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"
xmlns:context="http://www.springframework.org/schema/context"
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/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="springConfig.xml"/>
<bean id="UserMapper" class="com.tintin.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="userMapper2" class="com.tintin.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFatory"/>
</bean>
</beans>
UserMapperImpl2.java(继承SqlSessionDaoSupport)
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> listUser() {
return getSqlSession().getMapper(UserMapper.class).listUser();
}
}
main.java
public static void main(String[] args) {
ClassP...Context classP...Context = new ClassP...Context("applicationContext.xml");
//方法二:
UserMapper userMapper = (UserMapper) classP...Context.getBean("userMapper2");
List<User> userList = userMapper.listUser();
for (User user : userList) {
System.out.println(user);
}
}
事务
<!--结合AOP实现事务的植入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transationManagger">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性: 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" propagation="REQUIRED"/>
<!--正常写下面一行即可:配置全部的方法-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.tintin.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>