Spring学习笔记
1.简介
spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。
官网地址:spring官网链接
中文文档:spring 中文文档
github:spring github链接
maven依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
2.IOC
控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是loC的另一种说法。没有loC的程序中,我们使用面向对象编程, 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
3.HelloSpring
1.编写一个简单的实体类
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 + '\'' +
'}';
}
}
2.编写一个配置文件
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="pojo.Hello">
<property name="str" value="spring"/>
</bean>
</beans>
bean标签的作用是创建对象,其中id相当于变量名,class就是类型的全限定名,property可以设置这个对象的属性,如果是具体的值如基本数据类型就用value设置,还可以用ref来引用Spring中已经创建好的对象。
3.测试
public class Mytest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello);
}
}
先拿到spring的容器ApplicationContext,然后需要什么就get什么。
4.IOC创建对象的方式
1.默认使用无参的构造器创建对象
2.如果想使用有参构造器创建对象,则通过以下的方式:
<bean id="hello" class="pojo.Hello">
<constructor-arg name="str" value="Spring"/>
</bean>
总结:配置文件被加载的时候,容器中管理的对象就已经初始化了!
5.spring配置
用于合作开发,可以导入别的配置文件
id是变量名,class是类型的全限定名,name可以给变量起别名。
也可以给变量起别名。
6.DI依赖注入
IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的。比如对象A需要操作数据库,以前我们总是要在A中自己编写代码来获得一个Connection对象,有了 spring我们就只需要告诉spring,A中需要一个Connection,至于这个Connection怎么构造,何时构造,A不需要知道。在系统运行时,spring会在适当的时候制造一个Connection,然后像打针一样,注射到A当中,这样就完成了对各个对象之间关系的控制。A需要依赖 Connection才能正常运行,而这个Connection是由spring注入到A中的,依赖注入的名字就这么来的。那么DI是如何实现的呢? Java 1.3之后一个重要特征是反射(reflection),它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性,spring就是通过反射来实现注入的。
6.1 构造器注入
前面已经说过,这里不再赘述。
6.2 Set方式注入(重点)
建立复杂实体类
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + 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> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
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;
}
}
<bean id="address" class="pojo.Address">
<property name="add" value="青岛市市北区"/>
</bean>
<bean id="student" class="pojo.Student">
<!--普通值注入-->
<property name="name" value="张三"/>
<!--Bean注入-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>红楼梦</value>
<value>水浒传</value>
<value>三国演义</value>
<value>西游记</value>
</array>
</property>
<!--List-->
<property name="hobbies">
<list>
<value>音乐</value>
<value>篮球</value>
<value>电影</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="身份证" value="634757834657834"/>
<entry key="银行卡" value="34678586378563478"/>
</map>
</property>
<!--Set-->
<property name="games">
<set>
<value>lol</value>
<value>coc</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="学号">1905110004</prop>
</props>
</property>
</bean>
6.3 拓展方式注入
p命名空间和c命名空间,详情见官方文档。
6.4 bean的作用域
1.单例模式(Spring默认机制:scope=“singleton”
2.原型模式(每次从容器中get的时候都会产生一个新对象):scope=“prototype”
3.其余的request、session、application原理与web中类似。
7.bean的自动装配
自动装配是Spring满足bean依赖的一种方式,Spring会在上下文中自动寻找,并自动给bean装配属性!
三种装配方式:
- 在xml中显示的配置
- 在java中显示的配置
- 隐式的自动装配bean(重要)
7.1 byName自动装配
会自动在容器上下文中寻找和自己对象set方法后面的值对应的beanid autowire="byName"
<bean id="dog" class="pojo.Dog" />
<bean id="cat" class="pojo.Cat" />
<bean id="person" class="pojo.Person" autowire="byName"/>
注意:需要保证所有bean的id唯一。
7.2 byType自动装配
会自动在容器上下文中寻找和自己对象的属性类型相同的bean
autowire="byType"
<bean id="dog" class="pojo.Dog" />
<bean id="cat" class="pojo.Cat" />
<bean id="person" class="pojo.Person" autowire="byType"/>
7.3注解实现自动装配
要想使用注解,必须将配置文件改成如下:
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
注意一定不要忘了context:annotation-config/
然后在实体类的属性前加上@AutoWired注解(如果环境比较复杂,自动装配无法通过一个注解@AutoWired完成时,我们可以使用@Qualifier(value=“xxx”)来配合@AutoWired指定一个唯一的bean对象注入!)
也可以使用@Required注解
问题:JDK11需要导入以下依赖才可以使用@Resource
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
@AutoWired和@Required的区别:@AutoWired先根据byType,再根据byName实现自动装配,而@Required正好相反。
8.spring注解开发
前提:在配置文件中加入下面这句话,扫描指定的包,指定包下的注解都会生效。
<context:component-scan base-package="pojo"/>
8.1@Component
@Component可以将bean交给spring托管,@Value可以实现简单的注入。
8.2衍生的注解
@Component有几个衍生的注解,按照mvc三层架构分层
- dao层:@Repository
- service层:@Service
- controller层:@Controller
这四个注解功能一样,都是将某个类注册到spring容器中,装配bean。
8.3自动装配
- @Autowired
- @Resource
- @Nullable:字段标记了这个注解,说明这个字段可以为null。
8.4作用域
- @Scope(“singleton”)或者prototype等
9.动态代理
10.AOP
在使用AOP编程前需要导入一个依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
10.1方式一:使用Spring的API接口
1.首先编写一个接口和他的实现类
public interface UserService {
public void add();
public void update();
public void delete();
public void query();
}
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("添加成功");
}
@Override
public void update() {
System.out.println("修改成功");
}
@Override
public void delete() {
System.out.println("删除成功");
}
@Override
public void query() {
System.out.println("查询成功");
}
}
2.然后编写需要拓展的业务,一个在前,一个在后
public class Log implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
//method:要执行的目标对象的方法
//objects:参数
//o:目标对象
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
//o是返回值
System.out.println("执行了"+method.getName()+"方法,返回结果为"+o);
}
}
3.然后在配置文件中注册bean并且实现aop(需要导入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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="pojo.service.UserServiceImpl"/>
<bean id="log" class="pojo.log.Log"/>
<bean id="afterLog" class="pojo.log.AfterLog"/>
<aop:config>
<!--切入点:expression表达式:execution(返回值 类名 方法名 参数) -->
<aop:pointcut id="pointcut" expression="execution(* pojo.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
4.测试
public class Mytest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//动态代理代理的是接口!!!
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
10.2方式二:自定义类
public class diy {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
<bean id="userService" class="pojo.service.UserServiceImpl"/>
<bean id="diy" class="pojo.diy"/>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="pointcut" expression="execution(* pojo.service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
10.3方式三:注解
首先开启注解支持
<aop:aspectj-autoproxy/>
@Aspect
public class diy {
@Before("execution(* pojo.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前");
}
@After("execution(* pojo.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("方法执行后");
}
}
11.整合Mybatis
导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
官方文档:mybatis-spring –
1.编写实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
2.编写接口和Mapper
public interface UserMapper {
public List<User> selectUser();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.UserMapper">
<select id="selectUser" resultType="pojo.User">
select * from mybatis.user;
</select>
</mapper>
3.编写spring-dao.xml配置文件(此处十分重要,一点要谨慎小心)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" default-autowire="byName"
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://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?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="qiujun1110"/>
</bean>
<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:mapper/UserMapper.xml"/>
</bean>
<!--SQLSessionTemplate就是我们用的SQLSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能用构造器注入,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
这样一来spring就完全整合了mybatis,之前的mybatis配置文件和mybatisUtils基本都用不到了。
4.编写一个UserMapperImpl
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
5.编写一个applicationContex.xml,导入spring-dao.xml,然后在这个配置文件中注册刚才编写的UserMapperImpl。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" default-autowire="byName"
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
6.测试
public class Mytest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContex.xml");
UserMapper usermapper = (UserMapper) context.getBean("userMapper");
List<User> users = usermapper.selectUser();
for(User user:users){
System.out.println(user);
}
}
}
12.声明式事务
修改spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.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?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="qiujun1110"/>
</bean>
<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:mapper/UserMapper.xml"/>
</bean>
<!--SQLSessionTemplate就是我们用的SQLSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能用构造器注入,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知(哪些方法需要配置事务)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
注意:在开始添加tx约束,然后分三步:配置声明式事务、配置事务通知、配置事务切入。