Spring 5基础
- spring是一个轻量级的,非入侵式的框架
- 控制反转(IOC),面向切面编程(AOP)
1.IOC 推导
package com.jf.dao;
public interface UserDao {
void getUser();
}
package com.jf.dao;
public class UserDaoImpl implements UserDao{
@Override
public void getUser() {
System.out.println("获取默认用户的数据");
}
}
package com.jf.service;
public interface UserService {
void getUser();
}
package com.jf.service;
import com.jf.dao.UserDao;
import com.jf.dao.UserDaoImpl;
import com.jf.dao.UserDaoMysqlIpml;
public class UserServiceImpl implements UserService{
private UserDao userDao;
@Override
public void getUser() {
userDao.getUser();
}
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
import com.jf.dao.UserDaoMysqlIpml;
import com.jf.dao.UserDaoOracleImpl;
import com.jf.service.UserServiceImpl;
public class MyTest {
public static void main(String[] args) {
//用户实际调用的是业务层,dao层不需要接触
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoOracleImpl());
userService.getUser();
}
}
2.hello Spring
package com.jf.pojo;
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 + '\'' +
'}';
}
}
<?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">
<!--使用Spring来创建对象,在spring这些都称为Bean
类型 变量名 = new 类型()
Bean = 对象 new Hello()
id=变量名
class= new 的对象
property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.jf.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
import com.jf.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
3.IOC创建对象的方式
1.使用无参构造创建对象,默认
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 第一种 下标赋值-->
<!-- <bean id="user" class="com.jf.pojo.User">-->
<!-- <constructor-arg index="0" value="张二"/>-->
<!-- </bean>-->
<!-- 第二种通过类型创建不建议使用-->
<!-- <bean id="user" class="com.jf.pojo.User">-->
<!-- <constructor-arg type="java.lang.String" value="张三"/>-->
<!-- </bean>-->
<!-- 第三种,直接通过参数名来设置-->
<bean id="user" class="com.jf.pojo.User">
<constructor-arg name="name" value="张三"/>
</bean>
</beans>
4.Spring 配置
别名
<alias name="user" alias="usrNew"/>
bean配置
<!-- id:bean的唯一标识符 也就是对象名
class:bean对象所对应的权限命名
name:也是别名
-->
<bean id="user" class="com.jf.pojo.User" name="userNew">
<constructor-arg name="name" value="张三"/>
</bean>
import
一般用于团队开发,可以将多个配置文件,导入合并为一个
<import resource="bean2.xml"/>
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
5.DI依赖注入环境
SET方式注入
- 依赖 :bean对象的创建依赖于容器
- 注入 :bean对象中所有属性,由容器决定
package com.jf.pojo;
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 + '\'' +
'}';
}
}
package com.jf.pojo;
import java.util.*;
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 +
'}';
}
}
<?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">
<bean name="address" class="com.jf.pojo.Address">
<property name="address" value="云南"/>
</bean>
<bean name="student" class="com.jf.pojo.Student">
<property name="name" value="张三"/>
<!-- bean注入,ref-->
<property name="address" ref="address"/>
<!-- 数组注入-->
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
<property name="hobbys">
<list>
<value>听歌</value>
<value>自驾游</value>
<value>旅游</value>
</list>
</property>
<property name="card">
<map>
<entry key="银行卡" value="12341234"/>
<entry key="身份证" value="12345123451234"/>
</map>
</property>
<property name="games">
<set>
<value>写字</value>
<value>代码</value>
</set>
</property>
<property name="wife">
<null/>
</property>
<property name="info">
<props>
<prop key="学号">20151239</prop>
<prop key="性别">男</prop>
<prop key="username">root</prop>
<prop key="password">root</prop>
</props>
</property>
</bean>
</beans>
import com.jf.pojo.Student;
import com.jf.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
6.bean 的作用域
原型模式:(Spring默认模式)
<bean id="user" class="com.jf.pojo.User" name="userNew" scope="prototype">
单例模式;(每次从容器中get的时候,都会产生一个新的对象)
<bean id="user" class="com.jf.pojo.User" name="userNew" scope="singleton">
request,session,application只能在web开发总用到
7.Bean 的自动装配
- 自动装配是Spring 满足bean依赖一种方式
- Spring会在上下文中自动寻找,并自动被bean装配属性
在Spring中有三种装配的方式
1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配
搭建环境
package com.jf.pojo;
public class Cat {
public void shout(){
System.out.println("miao");
}
}
package com.jf.pojo;
public class Dog {
public void shout(){
System.out.println("wang");
}
}
<bean id="cat" class="com.jf.pojo.Cat"/>
<bean id="dog" class="com.jf.pojo.Dog"/>
<bean id="people" class="com.jf.pojo.people">
<property name="name" value="小k"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
import com.jf.pojo.Student;
import com.jf.pojo.User;
import com.jf.pojo.people;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
people people = context.getBean("people", people.class);
people.getCat().shout();
people.getDog().shout();
}
}
byName
<!-- byname:会自动在上下文中查找,和自己对象set方法后面的值对应的beanid-->
<bean id="people" class="com.jf.pojo.people" autowire="byName"/>
byType
<bean class="com.jf.pojo.Cat"/>
<bean class="com.jf.pojo.Dog"/>
<!-- byname:会自动在上下文中查找,和自己对象set方法后面的值对应的beanid
byType:会自动在上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.jf.pojo.people" autowire="byType">
<property name="name" value="小k"/>
</bean>
</beans>
小结:
byname:需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
bytype:需要保证所有的class唯一,并且这个bean需要和自动注入的属性的类型一致
7.1使用注解自动装配
使用注解须知:
1.导入约束
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"
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>
@Autowired
可以直接上属性上使用,也可以在set方式中使用
使用Autowired可以不用编写set方法,前提是这个自动装配的属性在Spring容器中使用,且符合名字byname
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成的时候,可以使用
@Qualifier(value = "值")取配置Autowired的使用,指定一个唯一的bean对象注入
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
<bean id="dog" class="com.jf.pojo.Dog"/>
<bean id="dog222" class="com.jf.pojo.Dog"/>
8 使用注解开发
1.导包
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/context/spring-aop.xsd
2.属性注入
package com.jf.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//Component 组件等价于<bean id="user" class="com.jf.pojo.User"/>
@Component
public class User {
public String name;
// 等价于<property name="name" value="张三"/>
@Value("张yi")
public void setName(String name) {
this.name = name;
}
}
3.衍生的注解
@Component有几个衍生的注解,web开发中,会安照mvc三层架构分层
-
dao (@Repository)
-
service (@Service)
-
controller(@controller)
这四个注解的功能都是一样的,都是代表将某个类注册到Spring中,装配bean
4.作用域
@Scope("singleton")
5.小结
xml域与注解
-
xml用来管理bean
-
注解只负责完成属性的注入
-
使用的时候,必须让注解生效,需要开启注解的支持
-
<!-- 指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.jf"/> <context:annotation-config/>
9.使用java的方式配置Spring
package com.jf.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//Component的意思是被Spring接管了,注册到了这个容器中
@Component
public class User {
@Value("张")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
package com.jf.config;
import com.jf.pojo.User;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
//意思是被Spring接管了,注册到了这个容器中,@Configurable代表是一个配置类,就和我们之前的bean.xml
@Configurable
@ComponentScan("com.jf.pojo")
@Import(AppConfig2.class)
public class AppConfig {
//注册一个bean 就相当于写的一个bean标签
//这个方法的名字,就相当于bean标签中id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象
}
}
package com.jf.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig2 {
}
import com.jf.config.AppConfig;
import com.jf.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
//如果完全使用了配置类方式,就只能ApplicationContext上下文获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}
10.代理模式
代理是SpringAOP的底层
代理模式分类
- 静态代理
- 动态代理
10.1静态代理
角色分析
-
抽象角色:一般会使用接口或者使用抽象类解决
-
真实角色:被代理角色
-
代理角色:代理真实角色,一般会做一些附属操作
-
客户:访问代理对象的人
代码步骤:
1.接口
package com.jf.demo01;
public interface Rent {
public void rent();
}
2.真实角色
package com.jf.demo01;
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东出租房子");
}
}
3.代理角色
package com.jf.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
seeHost();
fare();
}
public void seeHost(){
System.out.println("看房");
}
public void fare(){
System.out.println("收中介费");
}
}
4.客户端访问代理角色
package com.jf.demo01;
public class Client {
public static void main(String[] args) {
Host host = new Host();
//代理 代理角色一般会有一些附属操作
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
代理模式的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍
加深理解:
package com.jf.demo02;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
package com.jf.demo02;
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("查询一个用户");
}
}
package com.jf.demo02;
public class UserServiceProxy implements UserService{
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public void add() {
log("add");
userService.add();
}
@Override
public void delete() {
log("delete");
userService.delete();
}
@Override
public void update() {
log("update");
userService.update();
}
@Override
public void query() {
log("query");
userService.query();
}
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
package com.jf.demo02;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
}
}
10.2动态代理类
动态代理的代理类是动态生成的,不是直接写好的
动态代理类分为两大类:
- 基于接口的动态代理---JDK动态代理
- 基于类的:cglib
- java字节码实现:javasist
需要了解两个类:Proxy:代理 InvocationHandler:调用处理程序
InvocationHandler
package com.jf.demo03;
public interface Rent {
public void rent();
}
package com.jf.demo03;
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东出租房子");
}
}
package com.jf.demo03;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
seeHouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介看房子");
}
public void fare(){
System.out.println("收中介费");
}
}
package com.jf.demo03;
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色:没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();//得到代理类,这里代理类是动态生成的
proxy.rent();
}
}
通用理解:
package com.jf.demo02;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
package com.jf.demo02;
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("查询一个用户");
}
}
package com.jf.demo04;
import com.jf.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//自动生成代理类
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 result = method.invoke(target, args);
log(method.getName());
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
package com.jf.demo04;
import com.jf.demo02.UserService;
import com.jf.demo02.UserServiceImpl;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
//代理角色;不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.delete();
}
}
动态代理类的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代替多个类,只要是实现了同一个接口即可
11使用Spring来实现AOP
方式一:使用Spring的api接口
<?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="userService" class="com.jf.service.UserServiceIpml"/>
<bean id="log" class="com.jf.log.Log"/>
<bean id="afterLog" class="com.jf.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!-- 配置aop:导入aop的约束-->
<aop:config>
<!-- 切入点expression:表达式execution:要返回的位置(修饰词,返回值,类名,方法名)-->
<aop:pointcut id="pointcut" expression="execution(* com.jf.service.UserServiceIpml.*(..))"/>
<!-- 执行环绕-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
package com.jf.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
package com.jf.service;
public class UserServiceIpml 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 select() {
System.out.println("查询一个用户");
}
}
package com.jf.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
package com.jf.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为"+returnValue);
}
}
import com.jf.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
}
方式二:自定义来实现AOP(主要是切面)
<!-- 方式二:自定义类-->
<bean id="diy" class="com.jf.diy.DiyPointCut"/>
<aop:config>
<!-- 自定义切面 ref要引用的类-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="point" expression="execution(* com.jf.service.UserServiceIpml.*(..))"/>
<!-- 通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
package com.jf.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
package com.jf.service;
public class UserServiceIpml 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 select() {
System.out.println("查询一个用户");
}
}
package com.jf.diy;
public class DiyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
import com.jf.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
}
方式三:使用注解实现
package com.jf.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.jf.service.UserServiceIpml.*(..))")
public void before(){
System.out.println("执行前");
}
@After("execution(* com.jf.service.UserServiceIpml.*(..))")
public void after(){
System.out.println("执行后");
}
//在环绕增强中,我们可以给定一个参数,代表我们要处理的点
@Around("execution(* com.jf.service.UserServiceIpml.*(..))")
public void around(ProceedingJoinPoint jp){
System.out.println("环绕前");
//执行方法
try {
Object proceed = jp.proceed();
Signature signature = jp.getSignature();//获得签名
System.out.println("signature"+signature);
System.out.println(proceed);
} catch (Throwable e) {
e.printStackTrace();
}
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 id="userService" class="com.jf.service.UserServiceIpml"/>
<bean id="log" class="com.jf.log.Log"/>
<bean id="afterLog" class="com.jf.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!-- 配置aop:导入aop的约束-->
<!-- <aop:config>-->
<!--<!– 切入点expression:表达式execution:要返回的位置(修饰词,返回值,类名,方法名)–>-->
<!-- <aop:pointcut id="pointcut" expression="execution(* com.jf.service.UserServiceIpml.*(..))"/>-->
<!--<!– 执行环绕–>-->
<!-- <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
<!-- <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>-->
<!-- </aop:config>-->
<!-- 方式二:自定义类-->
<bean id="diy" class="com.jf.diy.DiyPointCut"/>
<bean id="annotationPointCut" class="com.jf.diy.AnnotationPointCut"/>
<!-- 开启注解支持-->
<aop:aspectj-autoproxy/>
<!-- <aop:config>-->
<!--<!– 自定义切面 ref要引用的类–>-->
<!-- <aop:aspect ref="diy">-->
<!--<!– 切入点–>-->
<!-- <aop:pointcut id="point" expression="execution(* com.jf.service.UserServiceIpml.*(..))"/>-->
<!--<!– 通知–>-->
<!-- <aop:before method="before" pointcut-ref="point"/>-->
<!-- <aop:after method="after" pointcut-ref="point"/>-->
<!-- </aop:aspect>-->
<!-- </aop:config>-->
</beans>
import com.jf.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
}
12 spring-mybatis
1.编写数据源配置
2.sqlSessionFactory
3.SqlSessionTemplate
4.需要给接口加实现类
5.将写的实现类,注入到Spring中
6.测试
<?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">
<!--DataSource:使用Spring的数据源替换mybatis的配置
使用spring提供的配置:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.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="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!-- 绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/jf/mapper/*.xml"/>
</bean>
<!-- SqlSessionTemplate:就是使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入sqlSessionFactory,因为没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
package com.jf.mapper;
import com.jf.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
//我们所有的操作,都使用sqlSession来执行,现在都使用SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
import com.jf.mapper.UserMapper;
import com.jf.pojo.User;
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.junit.Test;
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 {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
package com.jf.mapper;
import com.jf.pojo.User;
import java.util.List;
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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.jf.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis.user;
</select>
</mapper>
<?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>
<typeAlias type="com.jf.pojo.User" alias="user"/>
</typeAliases>
</configuration>
<?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">
<!--DataSource:使用Spring的数据源替换mybatis的配置
使用spring提供的配置:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.jf.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
.SqlSessionDaoSupport
package com.jf.mapper;
import com.jf.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
<?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">
<!--DataSource:使用Spring的数据源替换mybatis的配置
使用spring提供的配置:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.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="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!-- 绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/jf/mapper/*.xml"/>
</bean>
<!--<!– SqlSessionTemplate:就是使用的sqlSession–>-->
<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
<!--<!– 只能使用构造器注入sqlSessionFactory,因为没有set方法–>-->
<!-- <constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!-- </bean>-->
</beans>
import com.jf.mapper.UserMapper;
import com.jf.pojo.User;
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.junit.Test;
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 {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
13声明式事务
回顾事务:
- 把一组业务当成一个业务来做,要么成功,要么都失败
- 确保完整性和一致性
事务的ACID原则
- 原子性
- 一致性
- 隔离性
- 持久性
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况下
- 不再spring中配置事务,就需要在代码中手动配置事务
- 事务在开发中十分重要
导入jar包
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</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.1.9.RELEASE</version>
</dependency>
<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.8.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
package com.jf.pojo;
public class User {
private int id;
private String name;
private String 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;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.jf.mapper;
import com.jf.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser(int id);
}
<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.jf.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from mybatis.user;
</select>
<insert id="addUser" parameterType="user">
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
</mapper>
package com.jf.mapper;
import com.jf.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
//我们所有的操作,都使用sqlSession来执行,现在都使用SqlSessionTemplate
@Override
public List<User> selectUser() {
User user = new User(7, "小王", "1234");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(4);
return mapper.selectUser();
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(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: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">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.jf.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
<?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>
<typeAlias type="com.jf.pojo.User" alias="user"/>
</typeAliases>
</configuration>
<?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:使用Spring的数据源替换mybatis的配置
使用spring提供的配置:org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.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="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!-- 绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/jf/mapper/*.xml"/>
</bean>
<!--<!– SqlSessionTemplate:就是使用的sqlSession–>-->
<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
<!--<!– 只能使用构造器注入sqlSessionFactory,因为没有set方法–>-->
<!-- <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="add" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务的切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.jf.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
import com.jf.mapper.UserMapper;
import com.jf.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
标签:Spring,void,基础,org,import,jf,com,public
From: https://www.cnblogs.com/huangjiangfei/p/18444519