解决企业开发应用的复杂性。即解决开发企业开发难度,减轻对项目模块之间的管理,类和类之间的管理,帮助开发人员创建对象,管理对象之间的关系。
【总结】Spring 就是一个轻量级的控制反转(IOC)和面向切面(AOP)编程的框架
- IOC:把之前通过new创建对象的方式交给Spring的xml配置文件或者注解来做
- AOP:将之前业务功能的扩展实现要改变源代码这一方式解决,不需要改变源代码即可实现功能增强
一、IOC
1.1 IOC本质和理论
【案例结构】
package com.xxxx.ioc.dao;
public interface userDao {
void getuse();
}
package com.xxxx.ioc.dao;
public class userDaoImpl implements userDao {
public void getuse() {
System.out.println("默认获取用户数据");
}
}
package com.xxxx.ioc.service;
public interface userService {
void getService();
}
package com.xxxx.ioc.service;
import com.xxxx.ioc.dao.userDao;
import com.xxxx.ioc.dao.userDaoImpl;
import com.xxxx.ioc.dao.userMysql;
public class userServiceImpl implements userService {
// 传统方法
// private userDao userdao = new userMysql();
// ioc:利用set方法进行值的动态注入,传统的方法是程序控制对象的创建再通过业务层的调用实现使用,现在通过set方法
// 将对象的赋值交给用户
private userDao userdao;
public void setUserdao(userDao userdao) {
this.userdao = userdao;
}
public void getService() {
// service层调dao层
userdao.getuse();
}
}
import com.xxxx.ioc.dao.userDaoImpl;
import com.xxxx.ioc.dao.userMysql;
import com.xxxx.ioc.service.userService;
import com.xxxx.ioc.service.userServiceImpl;
public class mytest {
public static void main(String[] args) {
// 1.传统方法
// 测试类相当于servlet
// 会创建service对象
// userService userservice = new userServiceImpl();
// userservice.getService();//会输出dao层的方法,service只做一件事:调用dao层
/*
* 当增加实现类比如userMysql时,用户想使用新的userMysql时,需要在service层重新获取该实现类对应的对象。
* 即,美增加一个实现类,用户想要使用时,都需要程序猿在代码出重新调用对应的实现类,如果想解决这个问题,
* 就需要在serviceimpl中想办法
* */
// 2. ioc
userServiceImpl userService = new userServiceImpl();
// ((userService)userservice).setUserdao(new userMysql());
userService.setUserdao(new userDaoImpl());
userService.getService();
}
}
【总结】
之前,程序是主动创建对象,控制权在程序员手上,当业务发生扩展,程序员需要更改程序的代码来实现扩展业务的需求。使用set注入后,程序不再具有主动性,而是变成了被动的接收对象,即程序员不用再去管理对象的创建,系统的耦合性大大降低,专注于业务扩展。IOC的控制反转就是说对象创建的控制权的反转。所谓的IOC就是对象由spring来创建,管理和装配
1.2 IOC操作–Bean管理
Bean管理是指俩个操作:一是对象的创建;二是属性的注入。而Bean管理操作方式有俩种:一是xml;二是基于注解方式。
1.2.1 IOC创建对象
1.2.1.1 默认使用无参构造
1.2.1.2 有参构造
- 下标赋值
<constructor-arg index="" value=""/>
- 类型赋值(不建议使用,容易出错)
<constructor-arg type="" value=""/>
- 参数名赋值
<constructor-arg name="" value=""/>
【注意事项】将多个配置文件将通过 < import resource=""/>导入合并为一个
1.2.2 注入属性
在IOC中,如果要实现属性的注入也就是依赖注入DI,需要在对象创建的基础之上。
1.2.2.1 set注入
原始的属性注入方式一:使用new创建对象,通过对象调用对应属性的set方法来对属性进行赋值。依赖注入的本质就是set注入。
1.2.2.2 构造器注入
原始的属性注入方式二:通过有参构造方法在创建对象时进行属性值的注入。
1.2.2.3 其它方式
c命名空间和p命名空间
1.3 Bean的作用域
1.4 Bean的自动装配
- 自动装配是spring满足bean依赖的一种方式
- spring会在上下文中自动寻找,并自动给bean装配属性
【装配方法】
- 在xml中显示的配置
- 在java中显示的配置
- 隐式的自动装配bean
通过autowire=""属性来实现自动装配。
(1)byName:会自动在上下文中寻找和自己对象的set方法后面的值对象的bean的id值
(2)byType:会自动在上下文中寻找和自己对象属性类型相同的的bean的class值 - 使用注解实现自动装配
【注意事项】
(1)导入约束
(2)配置注解支持 < context:annotation-config/ >
(3)在对应的类添加@autowired
(4)当有多个对象(id不同class相同)需要自动装配时,除了(3)之外,还需要再添加@qualifier(value=“id值”)
<?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/beans/spring-context.xsd">
<context:annotation-config/>
</beans>
- @autowired和@qualifier是spring下的一套自动装配方法,java包下的@resource不用导包即可实现。如果出现4.(4)的情况,通过添加name属性来解决。
2.6 使用注解开发
在spring4之后,要使用注解开发,必须要确保导入AOP包以及context注解的支持
- @Component,放在类上,就相当于bean,如果要赋值可以在set方法上或者属性定义语句上添加@value("")来赋值
- @Component的衍生注解,分别是dao层的@@Repository、service层的@Service和controller层的@Controller,这几个注解功能都一样,都代表将某个类装配到spring容器中
2.7 使用java的方式配置Spring
三、AOP
3.1代理模式
代理模式是面向切面编程的底层实现。面试必问【AOP和MVC】
【代理模式的作用】
- 功能增强:在你原有的功能上,增加了额外的功能。新增加的概念叫做功能增强
- 控制访问:代理类不让你访问目标,例如商家不让用户访问厂家
【实现的方式】
- 静态代理:代理类是自己手工实现的,自己创建一个java类,表示代理类;同时要代理的目标类是确定的。
3.1.1 静态代理
【角色分析】
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色
- 客户:访问代理对象的人
【代理的好处】
- 可以使真实角色的操作更加纯粹
- 公共业务交给代理角色,实现业务的分工
- 公共业务发生拓展的时候,方便集中管理
【注意】个人理解,代理和IOC差不多
【代理的缺点】一个真是角色就会产生一个代理角色,代码量翻倍,开发效率变低。
3.1.2 动态代理
- 动态代理和静态代理角色一样
- 动态代理的类是动态生成的,不是直接写好的
- 动态代理分为两大类,一类是基于接口的动态代理,一类是基于类的动态代理。基于接口的动态代理是基于JDK的动态代理,基于类的是依赖cglib。还有一类是通过java字节码中的javasist来实现的(Jboss服务器)。
基础类:Proxy,InvocationHandler,Method
【Method】
package cn.java_class.agent_class;
import java.lang.reflect.Method;
public class Hellotest1 {
public static void main(String[] args) throws Exception {
// 普通方法实现使用接口中的实现类的方法是new对象来调用,现在使用反射机制来实现
// Hello helloimpl = new Helloimpl1();
Hello helloimpl = new Helloimpl2();
Method method = Hello.class.getMethod("hello", String.class);
method.invoke(helloimpl, "张三");
}
}
【InvocationHandler】
InvocationHandler是一个接口,译为调用处理器,表示你的代理要干什么。有且只有一个方法invoke(),该方法用来表示代理对象要执行的功能代码。即代理类要完成的概念
public Object invoke(Object proxy, Method method, Object[] args)
参数:
- Object proxy:jdk创建的代理对象,无需赋值
- Method method:目标类中的方法
- Object[] args:方法的参数
【Proxy】
通过静态方法newProxyInstance()创建代理对象。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
参数:
- ClassLoader loader:向内存中加载对象
- Class<?>[] interfaces:目标对象对应的接口
- InvocationHandler h:自己写的代理类要完成的功能
package cn.java_class.agent_class;
public interface Hello {
public void hello(String name);
}
package cn.java_class.agent_class;
public class Helloimpl1 implements Hello {
@Override
public void hello(String name) {
System.out.println("Helloimpl1你好:"+name);
}
}
package cn.java_class.agent_class;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class handlerdemo1 implements InvocationHandler {
//被代理的接口
private Hello hello;
public void setHello(Hello hello) {
this.hello = hello;
}
// 生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),hello.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(hello, args);
return result;
}
}
package cn.java_class.agent_class;
public class Hellotest2 {
public static void main(String[] args) throws Exception {
/*
动态代理的是实现步骤:
1. 创建接口,定义目标类要完成的功能
2. 创建目标类实现接口
3. 创建invocationhandler的实现类,在invoke中完成功能
* */
Helloimpl1 h1 = new Helloimpl1();
handlerdemo1 handlerdemo1 = new handlerdemo1();
handlerdemo1.setHello(h1);
Hello proxy = (Hello) handlerdemo1.getProxy();
proxy.hello("ss"); //运行到这里会跳到handler的invoke方法执行,具体原理没有查到
}
}
3.2 AOP
3.2.1 概述
- 面向切面编程,利用aop对业务逻辑的各个方面进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,提高开发的效率
- 通俗的说,AOP就是通过不修改源代码,在主干功能中添加新的功能。
3.2.2 实现方法
- 使用spring的API接口
- 自定义实现AOP
- 使用注解方式
四、Mybatis-Spring
Mybatis-Spring类会将mybatis无缝整合到spring中,允许mybatis参与到spring的事务管理当中,创建映射器mapper和sqlsession并注入到bean中。要在spring中使用mybatis,必须要在上下文中定义sqlsessionfactory和至少一个数据映射器类。
4.1实现过程
【1.导入依赖】
<!-- 导入依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring操作数据库的话还需要一个spring-jdbc的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
【2.资源过滤配置】
<!--maven的资源过滤问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
【3.编写对应的配置文件】
在mybatis中,步骤1定义数据源是写在mybatis-config.xml中的,步骤2-3是封装好的工具类,相当于JDBC中的getConnection。
<?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">
<!--1. 定义datasource:使用Spring的数据源替换Mabatis的配置(dbcp,c3p0),我们这里使用spring提供的jdbc-->
<bean id="owedataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--2.创建sqlsessionfactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="owedataSource"/>
<!-- 绑定mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/xxxx/mapper/*.xml"/>
</bean>
<!--3.创建sqlsession,SqlSessionTemplate就是mybatis中的sqlsession-->
<bean id="sqlsession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="bookmapper" class="com.xxxx.mapper.BooksMapperImpl">
<property name="sqlsession" ref="sqlsession"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.xxxx.pojo"/>
</typeAliases>
</configuration>
【4.实体类】
package com.xxxx.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
【5.mapper】
package com.xxxx.mapper;
import com.xxxx.pojo.Books;
import java.util.List;
public interface BooksMapper {
List<Books> getAllBooks();
}
package com.xxxx.mapper;
import com.xxxx.pojo.Books;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class BooksMapperImpl implements BooksMapper {
private SqlSessionTemplate sqlsession;
public void setSqlsession(SqlSessionTemplate sqlsession) {
this.sqlsession = sqlsession;
}
public List<Books> getAllBooks() {
BooksMapper mapper = sqlsession.getMapper(BooksMapper.class);
return mapper.getAllBooks();
}
}
<?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">
<!--mybatis就是把一个impl实现类变为一个xml的配置文件-->
<mapper namespace="com.xxxx.mapper.BooksMapper">
<select id="getAllBooks" resultType="books">
select * from ssmbuild.books;
</select>
</mapper>
【6.测试类】
import com.xxxx.mapper.BooksMapper;
import com.xxxx.pojo.Books;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class mytest {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
BooksMapper bookmapper = context.getBean("bookmapper", BooksMapper.class);
List<Books> allBooks = bookmapper.getAllBooks();
for (Books allBook : allBooks) {
System.out.println(allBook);
}
}
}