6.1.spring中pom.xml的配置
spring官方文档在这个链接https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
2.beans.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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="hello" class="com.kuang.pojo.User">
<property name="name" value="Spring"/>
</bean>
</beans>
//id:相当于变量名
//class 相当于new 类()
</beans>
3.SpringTest测试代码:
public void Test(){
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
User name= (User) context.getBean("hello");
System.out.println(name.toString());
}
4.ioc创建对象的方式
1.使用无参构造创建对象
<bean id="construct" class="com.kuang.yb.construct">
</bean>
2.加入要使用有参构造
bean.xml:
<bean id="construct1" class="com.kuang.yb.construct">
<constructor-arg name="id" value="1"></constructor-arg>
<constructor-arg name="name" value="yx"></constructor-arg>
</bean>
3.set注入
<bean id="name" class="com.kuang.pojo.student">
<property name="name" value="杨欣小胖胖"></property>//value赋值
<property name="address" ref="adress"></property>//ref引用赋值
<property name="books">//数组赋值
<array>
<value>库里</value>
<value>汤普森</value>
<value>格林</value>
</array>
</property>
<property name="hobbys" >list集合赋值
<list>
<value>打篮球</value>
<value>踢足球</value>
</list>
</property>
<property name="card" >//map集合赋值
<map>
<entry key="中国邮政银行" value="142155376417"/>
<entry key="中国建设银行" value="2165327846328"/>
</map>
</property>
//set注入
<property name="games">
<set>
<value>2k</value>
</set>
</property>
</bean>
</beans>
4.p命名空间,c命名空间
1.p命名空间
加入约束: xmlns:p=“http://www.springframework.org/schema/p”
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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-3.0.xsd">
<!--p命名空间直接注入属性-->
<bean id="namespace" class="com.kuang.namespace.Student" p:grade="100" p:id="1" p:name="易彪"></bean>
<!--c命名空间通过构造器注入-->
<bean id="namespace1" class="com.kuang.namespace.Student" c:name="杨欣" c:id="2"></bean>
</beans>
2.c命名空间
加入约束: xmlns:c=“http://www.springframework.org/schema/c”
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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-3.0.xsd">
<!--p命名空间直接注入属性-->
<bean id="namespace" class="com.kuang.namespace.Student" p:grade="100" p:id="1" p:name="易彪"></bean>
<!--c命名空间通过构造器注入-->
<bean id="namespace1" class="com.kuang.namespace.Student" c:name="杨欣" c:id="2"></bean>
</beans>
5.bean的作用域:
1.单例模式:每次去容器中get时都是拿到原来的对象 加入scope="singleton"即为单例模式
<bean id="namespace" class="com.kuang.namespace.Student" p:grade="100" p:id="1" p:name="易彪" scope="singleton"></bean>
2.原型模式:每次去容器中get时都是拿到不同的对象 加入scope="prototype"即为原型模式
<bean id="namespace1" class="com.kuang.namespace.Student" c:name="杨欣" c:id="2" scope="prototype"></bean>
6.自动装配
1.beans.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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dog" class="com.baidu.pojo.Dog"></bean>
<bean id="cat" class="com.baidu.pojo.Cat"></bean>
<!--
byName:找与set方法后面名字相同的bean id;
byType:找到与自己对象属性类型相同的bena id;
-->
<bean id="people" class="com.baidu.pojo.People" autowire="byName">
<property name="name" value="杨欣"></property>
</bean>
</beans>
2.实体类
package com.baidu.pojo;
public class People {
String name;
Dog dog;
Cat cat;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
}
//
package com.baidu.pojo;
public class Dog{
public Dog(){
}
public void shou(){
System.out.println("汪汪汪");
}
}
///
package com.baidu.pojo;
public class Cat {
public Cat(){
}
public void shou(){
System.out.println("喵喵喵");
}
}
7.使用注解自动装配
1.导入注解约束
<?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:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解支持 -->
<context:annotation-config/>
<bean id="cat" class="com.baidu.pojo.Cat" />
<bean id="dog" class="com.baidu.pojo.Dog" />
<bean id="people" class="com.baidu.pojo.People" />
</beans>
2.配置注解支持 context:annotation-config/
3.实体类
package com.baidu.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
String name;
@Autowired//自动装配属性
Dog dog;
@Autowired
@Qualifier("cat111")//识别是那个bean的id
Cat cat;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
}
总结 @Autowired:直接通过byType查找,加入 @Qualifier(“cat111”)通过byName查找
@Resource:先通过byName查找,如果找不到,在通过byType查找
8.Spring注解开发
@Component
<!--自动扫描com.baidu,pojo下面的包-->
<context:component-scan base-package="com.baidu.pojo"/>
//配套使用,在类上加入Component 说明可以被自动扫描到
@Repository//仓库类dao层
@@Controller//controller层
@Service//service层
9.javaConfig实现配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WbvukqGm-1604053553040)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20201015165916133.png)]
test代码
public void test02(){
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Student student = context.getBean("getStudent",Student.class);
System.out.println(student.id);
}
10.静态代理模式
源码:
package com.kuang.demo01;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加方法");
}
public void delete() {
System.out.println("删除方法");
}
public void insert(){
System.out.println("插入方法");
}
public void update(){
System.out.println("更新方法");
}
}
/
package com.kuang.demo01;
public class UserServiceProxy implements UserService {
private UserService uservice;
public void setUservice(UserService uservice){
this.uservice=uservice;
}
public void add() {
System.out.println("测试代理模式");
uservice.add();
}
public void delete() {
}
public void insert() {
}
public void update() {
}
}
///
public static void main(String[] args) {
/*userService.update();
userService.delete();
userService.add();*/
UserService userService=new UserServiceImpl();
UserServiceProxy proxy=new UserServiceProxy();
proxy.setUservice(userService);
proxy.add();//通过代理实现add()方法
}
11.动态代理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3OuZyUYf-1604053553042)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20201015195547967.png)]
代码实现:(代理的是接口)
package com.kuang.demo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//代理类实现InvocationHandler接口,重写方法
public class Proxy implements InvocationHandler {
//被代理的对象
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理类的方法
public Object getProxy(){
/*
第一个参数获得类加载器
第二个参数被代理的对象的接口
第三个参数 InvocationHandler
* */
return java.lang.reflect.Proxy.
newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并得到返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(rent,args);
}
}
///
package com.kuang.demo;
public class Client {
public static void main(String[] args) {
//真实角色
Host host =new Host();
//通过调用程序处理角色来处理我们要调用的接口
Proxy in=new Proxy();
in.setRent(host);
//得到代理对象
Rent proxy = (Rent) in.getProxy();
proxy.rent();
}
}
动态代理utils:
package com.kuang.utils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class utilsProxy implements InvocationHandler {
//要调用的接口对象
private Object target;
public void setTarget(Object target){
this.target=target;
}
//生成代理类的方法
public Object getUserServiceProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target,args);
}
}
12.AOP
1.使用原生spring接口实现
1.测试代码
public class MyTest {
@Test
public void test01(){
ApplicationContext context =
new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserService uservice= (UserService) context.getBean("UserService");
uservice.delete();
///
com.baidu.service.UserServiceImpl的delete调用删除方法
com.baidu.service.UserServiceImpl执行了delete返回结果为null
}
2.beans.xml
<!-- 开启注解支持 -->
<context:annotation-config/>
<context:component-scan base-package="com.baidu.log"/>
<context:component-scan base-package="com.baidu.service"/>
<bean id="UserService" class="com.baidu.service.UserServiceImpl"/>
<aop:config>
<!--
1、execution(): 表达式主体。
2、第一个*号:表示返回类型,*号表示所有的类型。
3、包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com.sample.service.impl包、子孙包下所有类的方法。
4、第二个*号:表示类名,*号表示所有的类。
5、*(..):最后这个星号表示方法名,*号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。
-->
<aop:pointcut id="pointcut" expression="execution(* com.baidu.service.*.*(..))"/>
<!--执行环绕-->advice-ref通知
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
2.使用自定义接口实现
1.bean.xml
<!--aop方式二自定义类实现-->
<aop:config>
<!--自定义切面要引用的类-->
<aop:aspect ref="log">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.baidu.service.*.*(..))"/>
<!--通知-->
<aop:before method="beforeLog" pointcut-ref="point"></aop:before>
<aop:after method="afterLog" pointcut-ref="point"></aop:after>
</aop:aspect>
</aop:config>
2.测试代码
public class MyTest {
@Test
public void test01(){
ApplicationContext context =
new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserService uservice= (UserService) context.getBean("UserService");
uservice.delete();
}
}
13.Spring-Mybatis整合方式一
1.bookMapperImpl类
package com.baidu.mapper;
import com.baidu.pojo.books;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class bookMapperImpl implements bookMapper {
private SqlSessionTemplate sqlsession;
public void setSqlsession(SqlSessionTemplate sqlsession) {
this.sqlsession = sqlsession;
}
public List<books> select() {
bookMapper mapper = sqlsession.getMapper(bookMapper.class);
return mapper.select();
}
}
2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringMybtis01</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>SpringMybatis02</module>
</modules>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
3.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解支持 -->
<context:annotation-config/>
<!--数据库连接注入-->
<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/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
<!--生成sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:MybatisConfig.xml"></property>
</bean>
<!--生成sqlsession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="bookServiceImpl" class="com.baidu.mapper.bookMapperImpl">
<property name="sqlsession" ref="sqlSession"/>
</bean>
</beans>
2.方式二SqlSessionDaoSupport
SqlSessionDaoSupport
是一个抽象的支持类,用来为你提供 SqlSession
。调用 getSqlSession()
方法你会得到一个 SqlSessionTemplate
,之后可以用于执行 SQL 方法,就像下面这样:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User getUser(String userId) {
return getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
}
}
在这个类里面,通常更倾向于使用 MapperFactoryBean
,因为它不需要额外的代码。但是,如果你需要在 DAO 中做其它非 MyBatis 的工作或需要一个非抽象的实现类,那么这个类就很有用了。
SqlSessionDaoSupport
需要通过属性设置一个 sqlSessionFactory
或 SqlSessionTemplate
。如果两个属性都被设置了,那么 SqlSessionFactory
将被忽略。
假设类 UserMapperImpl
是 SqlSessionDaoSupport
的子类,可以编写如下的 Spring 配置来执行设置:
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
14.事务
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eXrrL7tk-1604053553045)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20201017215851987.png)]
配置事务
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iSPib7ax-1604053553048)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20201017225603809.png)]
<!--要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager 对象:-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!--配置事务传播特性-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txpoint" expression="execution(* com.baidu.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpoint"/>
</aop:config>
```