Spring
1、Spring使用
优点:
- Spring是一个开源免费的容器(框架)
- Spring是轻量式、非入侵式的框架
- 控制饭庄(IOC)、面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
2、IOC
IOC本质
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HQXLePHU-1629369461223)(C:\Users\rxp\AppData\Roaming\Typora\typora-user-images\image-20210819160400223.png)]
3、依赖注入
构造函数参数类型匹配
构造函数参数名称
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>
set依赖注入
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address.toString() +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
<bean id="address" class="com.pxr.bean.Address">
<property name="address" value="天津"/>
</bean>
<bean id="student" class="com.pxr.bean.Student">
<!-- collaborators and configuration for this bean go here -->
<!--属性注入-->
<property name="name" value="张杰"/>
<!--实体注入-->
<property name="address" ref="address"/>
<!--数组注入-->
<property name="books">
<array>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--List-->
<property name="hobbys">
<list>
<value>唱歌</value>
<value>打球</value>
<value>游泳</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="电话" value="15095513645"/>
<entry key="证件号" value="1511545155"/>
</map>
</property>
<!--Set-->
<property name="games">
<set>
<value>姓名</value>
<value>年龄</value>
<value>学号</value>
</set>
</property>
<!--String-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="账号">858585858585</prop>
<prop key="年龄">85</prop>
</props>
</property>
</bean>
4、代理模式
静态代理
动态代理
public interface Rent {
void rent();
}
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
public class Proxy implements Rent{
private Host host;
public Proxy(Host host) {
this.host = host;
}
public Proxy() {
}
public Host getHost() {
return host;
}
public void setHost(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
}
}
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
5、AOP
5.1 AOP在Spring中的作用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g5HysrHH-1629369461234)(C:\Users\rxp\AppData\Roaming\Typora\typora-user-images\image-20210819141452160.png)]
5.2 导包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
5.3 方式一:使用API接口
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
}
}
public class Log implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(objects.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
<?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.pxr.service.UserServiceImpl"/>
<bean id="log" class="com.pxr.log.Log"/>
<bean id="afterLog" class="com.pxr.log.AfterLog"/>
<!-- 配置AOP-->
<aop:config>
<!-- 切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.pxr.service.UserServiceImpl.*(..))"></aop:pointcut>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
5.4 方式二:自定义类(推介)
public class DiyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
<bean id="diy" class="com.pxr.diy.DiyPointCut"/> <aop:config> <!-- 自定义切面,ref要引用的类--> <aop:aspect ref="diy"> <!-- 切入点--> <aop:pointcut id="point" expression="execution(* com.pxr.service.UserServiceImpl.*(..))"/> <!-- 通知--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>
5.5 方式三:使用注解
@Aspect //标注这是个切面类public class AnnoationPointCut { @Before("execution(* com.pxr.service.UserServiceImpl.*(..))") public void before(){ System.out.println("方法执行前"); } @After("execution(* com.pxr.service.UserServiceImpl.*(..))") public void after(){ System.out.println("方法执行后"); }}
<!-- 方式三:开启注解支持--> <bean id="an" class="com.pxr.diy.AnnoationPointCut"/> <aop:aspectj-autoproxy/>
6、整合MyBatis
- 导包
- 编写数据源dataSourse
- sqlSessionFactory
- SqlSessionTemplate
- 测试
spring-mybatis.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数据源--> <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/girls?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="root123"/> </bean> <!-- sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定mybatis配置-->
<property name="configLocation" value="classpath:mybatis.xml"/> <property name="mapperLocations" value="classpath:com/pxr/mapper/*.xml"/> </bean> <!--SqlSessionTemplate:sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <bean id="userMapper" class="com.pxr.dao.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean></beans>
7、Spring中事务管理
事务原则:ACID
- 原子性
- 一致性
- 隔离性
- 持久性
事务分类:
声明式事务(AOP),编程式事务
xml.配置
<!--配置声明式事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"/> </bean> <!--结合AOP实现事物的织入--> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--给那些方法配置事务--> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--配置事务切入--> <aop:config> <aop:pointcut id="txPointCute" expression="execution(* com.pxr.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCute"/> </aop:config>
<?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" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 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/girls?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="root123"/> </bean> <!-- sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"/> <!--绑定mybatis配置--> <property name="configLocation" value="classpath:mybatis.xml"/> <property name="mapperLocations" value="classpath:com/pxr/mapper/*.xml"/> </bean> <!--SqlSessionTemplate:sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <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">
<!--给那些方法配置事务--> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>
<!--配置事务切入--> <aop:config> <aop:pointcut id="txPointCute" expression="execution(* com.pxr.dao.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCute"/> </aop:config> <bean id="userMapper" class="com.pxr.dao.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean></beans>