Spring5学习总结(一)

一、Spring

Spring是轻量级的开源的JavaEE框架,Spring可以解决企业应用开发的复杂性。

Spring核心部分:

  1. IOC(Inversion of Control):控制反转,把创建对象的过程交给Spring进行管理。
  2. AOP(Aspect Oriented Programming):偏向切面编程,在不修改源码下对功能进行增强

Spring特点:

  • 方便解耦,简化开发
  • Aop编程支持
  • 方便程序测试
  • 方便和其他框架进行整合
  • 方便进行事务操作
  • 降低API开发难度

Spring框架下载:
https://repo.spring.io/release/org/springframework/spring/

二、Spring简单案例

前提:导入相应jar包

<!--Spring配置文件-->
<?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"> <!--配置User对象创建--> 

<bean id="user" class="com.dxs.spring5.User"></bean> </beans>
public class User {
    
     public void add() {
    
     			
		System.out.println("add"); 
	}
}
//测试代码
@Test public void testAdd() {
    
     
	//1 加载spring配置文件 
	ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); 
	
	//2 获取配置创建的对象 
	User user = context.getBean("user", User.class); 
	
	System.out.println(user); 
	user.add(); 
}

三、IOC

1.IOC概念和原理

控制反转。把对象创建和对象之间的调用过程,交给Spring进行管理。使用IOC目的:为了耦合度降低

IOC底层原理:反射、工厂模式、xml解析。

通过xml配置文件创建响应对象,为降低耦合度(DAO层与Service层之间),使用工厂模式来创建对象,为进一步降低耦合度(Factory类和Service层),工厂类中使用反射来获取对象。
在这里插入图片描述

2.IOC容器

IOC思想基于IOC容器完成,IOC容器底层就是对象工厂。

Spring提供IOC容器实现两种方式:(两个接口)

  1. BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用
    加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象
  2. ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用
    加载配置文件时候就会把在配置文件对象进行创建
    一般推荐ApplicationContext,尽量让创建的耗时操作在后台完成,而不影响前端页面的交互

下图为ApplicationContext实现类:
在这里插入图片描述

3.IOC操作Bean管理

Bean管理:指的是两个操作。Spring创建对象;Spring注入属性

Bean操作的实现方式

  1. 基于xml配置文件
  2. 基于注解方式

(1)基于xml配置文件

1.基于xml配置文件创建对象

<bean id="user" class="com.dxs.spring5.User"></bean> </beans>

在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建。

在bean标签有很多属性,常用的属性:

  • id属性:唯一标识
  • class属性:类全路径(包类路径)

创建对象时候,默认也是执行无参数构造方法完成对象创建

2.基于xml配置文件注入属性
两种属性注入方式:

  1. 使用set方法
  2. 使用有参数构造进行注入

示例一:

<!--set方法注入属性--> 
<bean id="book" class="com.dxs.spring5.Book"> 
	<!--使用property完成属性注入 name:类里面属性名称 value:向属性注入的值 --> 
	<property name="bname" value="易筋经"></property> 
	<property name="bauthor" value="达摩老祖"></property> 
</bean>
public class Book {
    
     
	//创建属性 
	private String bname; 
	private String bauthor; 
	//创建属性对应的set方法 
	public void setBname(String bname) {
    
     this.bname = bname; } 
	public void setBauthor(String bauthor) {
    
     this.bauthor = bauthor; } 
}

示例二:

<!--有参数构造注入属性--> 
<bean id="orders" class="com.dxs.spring5.Orders">
	 <constructor-arg name="oname" value="电脑"></constructor-arg> 
	 <constructor-arg name="address" value="China"></constructor-arg> 
 </bean>
public class Orders {
    
     
	//属性 
	private String oname; 
	private String address; 
	//有参数构造 
	public Orders(String oname,String address) 
	{
    
     this.oname = oname; this.address = address; } 
}
null注入
<!--默认也是null的-->
<!--null值--> 
    <property name="address"> <null/> </property>
特殊符号注入
<!--属性值包含特殊符号 
1 把<>进行转义 &lt; &gt; 
2 把带特殊符号内容写到CDATA --> 
<property name="address"> <value><![CDATA[<<南京>>]]></value> </property>
外部bean注入(属性为对象)
public class UserService {
    
     
	//创建UserDao类型属性,生成set方法 
	private UserDao userDao; 
	public void setUserDao(UserDao userDao) {
    
     this.userDao = userDao; } 
	
	public void add() {
    
     
		System.out.println("service add"); userDao.update(); 
	} 
}
<!--1 service和dao对象创建--> 
<bean id="userService" class="com.dxs.spring5.service.UserService"> 
	<!--注入userDao对象 name属性:类里面属性名称 ref属性:创建userDao对象bean标签id值 --> 
	<property name="userDao" ref="userDaoImpl"></property> 
</bean> 

<bean id="userDaoImpl" class="com.dxs.spring5.dao.UserDaoImpl"></bean>
内部bean注入
public class Dept {
    
     
	private String dname; 
	public void setDname(String dname) {
    
     this.dname = dname; } 
} 

//员工类 
public class Emp {
    
     
	private String ename; 
	private String gender; 
	
	//员工属于某一个部门,使用对象形式表示 
	private Dept dept; 
	public void setDept(Dept dept) {
    
     this.dept = dept; } 
	public void setEname(String ename) {
    
     this.ename = ename; } 
	public void setGender(String gender) {
    
     this.gender = gender;
	} 
}
<bean id="emp" class="com.dxs.spring5.bean.Emp"> 
<!--设置两个普通属性--> 
	<property name="ename" value="lucy"></property> 
	<property name="gender" value=""></property> 
	
	<!--设置对象类型属性--> 
	<property name="dept"> 
		<bean id="dept" class="com.dxs.spring5.bean.Dept"> 
			<property name="dname" value="安保部"></property> 
		</bean> 
	</property> 
</bean>
级联赋值
<!--级联赋值--> 
<bean id="emp" class="com.dxs.spring5.bean.Emp"> 
	<!--设置两个普通属性--> 
	<property name="ename" value="lucy"></property>
	<property name="gender" value=""></property> 

	<!--级联赋值--> 
	<property name="dept" ref="dept"></property> 
	<property name="dept.dname" value="技术部"></property> 
</bean> 

<bean id="dept" class="com.dxs.spring5.bean.Dept"> 
	<property name="dname" value="财务部"></property> 
</bean>
数组、List、Map注入
public class Stu {
    
     
//1 数组类型属性 
private String[] courses; 

//2 list集合类型属性 
private List<String> list; 

//3 map集合类型属性 
private Map<String,String> maps; 

//4 set集合类型属性 
private Set<String> sets; 

public void setSets(Set<String> sets) {
    
     this.sets = sets; } 
public void setCourses(String[] courses) {
    
     this.courses = courses; } 
public void setList(List<String> list) {
    
     this.list = list; } 
public void setMaps(Map<String, String> maps) {
    
     this.maps = maps; } }
<!--1 集合类型属性注入--> 
<bean id="stu" class="com.dxs.spring5.collectiontype.Stu"> 
	<!--数组类型属性注入--> 
	<property name="courses"> 
		<array> 
		<value>java课程</value> 
		<value>数据库课程</value> 
		</array> 
	</property> 
	
	<!--list类型属性注入--> 
	<property name="list"> 
		<list>
		<value>张三</value> 
		<value>小三</value> 
		</list> 
	</property> 
	
	<!--map类型属性注入--> 
	<property name="maps"> 
		<map> 
		<entry key="JAVA" value="java"></entry> 
		<entry key="PHP" value="php"></entry> 
		</map> 
	</property> 
	
	<!--set类型属性注入--> 
	<property name="sets"> 
		<set> 
		<value>MySQL</value> 
		<value>Redis</value> 
		</set> 
	</property> 
</bean>
<!--创建多个course对象--> 
<!--list集合中是course对象-->
<bean id="course1" class="com.dxs.spring5.collectiontype.Course"> 
	<property name="cname" value="Spring5框架"></property> 
</bean> 

<bean id="course2" class="com.dxs.spring5.collectiontype.Course"> 
	<property name="cname" value="MyBatis框架"></property> 
</bean> 

<!--注入list集合类型,值是对象--> 
<property name="courseList"> 
	<list> 
		<ref bean="course1"></ref> 
		<ref bean="course2"></ref> 
	</list> 
</property>
<!--在spring配置文件中引入名称空间 util-->
<!--使用util标签完成list集合注入提取-->

<?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:util="http://www.springframework.org/schema/util" 


xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<!--1 提取list集合类型属性注入--> 
<util:list id="bookList">
	<value>易筋经</value>
	 <value>九阴真经</value> 
	 <value>九阳神功</value> 
 </util:list> 

<!--2 提取list集合类型属性注入使用--> 
<bean id="book" class="com.dxs.spring5.collectiontype.Book"> 
	<property name="list" ref="bookList"></property> 
</bean>
FactoryBean

Spring有两种类型bean,一种普通bean,另外一种工厂bean(FactoryBean)

  1. 普通bean:在配置文件中定义bean类型就是返回类型
  2. 工厂bean:在配置文件定义bean类型可以和返回类型不一样

实现步骤:

  1. 创建类,让这个类作为工厂bean,实现接口 FactoryBean
  2. 实现接口里面的方法,在实现的方法中定义返回的另一种bean类型
public class MyBean implements FactoryBean<Course> {
    
     
//定义返回bean 
@Override 
public Course getObject() throws Exception {
    
     
	Course course = new Course(); 
	course.setCname("abc"); 
	return course; 
} 

@Override 
public Class<?> getObjectType() 
{
    
     return null; } 

@Override 
public boolean isSingleton() 
{
    
     return false; } }
<bean id="myBean" class="com.dxs.spring5.factorybean.MyBean"> </bean>
@Test public void test3() {
    
     
	ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); 
	Course course = context.getBean("myBean", Course.class); 
	System.out.println(course); 
}
bean的作用域

在Spring里面,默认情况下,bean是单实例对象,即如果获取相同id的bean对象,返回的对象是相同的(地址相同)。

在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例。

<!--
默认值,singleton,表示是单实例对象
prototype,表示是多实例对象
-->

<bean id="book" class="com.dxs.spring5.Book" scope="prototype"></bean>

区别:

  1. singleton单实例,prototype多实例
  2. 设置scope值是singleton时候,加载spring配置文件时候就会创建单实例对象;设置scope值是prototype时候,不是在加载spring配置文件时候创建对象,在调用getBean方法时候创建多实例对象
bean生命周期(重点)

生命周期:从对象创建到对象销毁的过程

bean生命周期

  1. 通过构造器创建bean实例(无参数构造)
  2. 为bean的属性设置值和对其他bean引用(调用set方法)
  3. 把bean实例传递bean后置处理器的方法postProcessBeforeInitialization
  4. 调用bean的初始化的方法(需要进行配置初始化的方法)
  5. 把bean实例传递bean后置处理器的方法 postProcessAfterInitialization
  6. bean可以使用了(对象获取)
  7. 当容器关闭时候,调用bean的销毁的方法(需要进行配置销毁的方法)

演示:

public class Orders {
    
    
	//无参数构造 
	public Orders() {
    
     System.out.println("第一步 执行无参数构造创建bean实例"); } 
	
	private String oname; 
	
	public void setOname(String oname) {
    
     
		this.oname = oname; 
		System.out.println("第二步 调用set方法设置属性值"); 
} 

	//创建执行的初始化的方法 
	public void initMethod() {
    
     
		System.out.println("第三步 执行初始化的方法"); 
	} 

	//创建执行的销毁的方法 
	public void destroyMethod() {
    
     
		System.out.println("第五步 执行销毁的方法"); 
	} 
}
public class MyBeanPost implements BeanPostProcessor {
    
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("在初始化之前执行");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("在初始化之后执行");
        return bean;
    }
}
<bean id="orders" class="com.dxs.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="dxs"></property>
    </bean>
@Test
    public void test4(){
    
    
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("4.获取bean实例对象");
        System.out.println(orders);
		
		//手动销毁
        context.close();
    }
xml自动装配

例如自动装配数据库信息(前提:导包)

#创建jdbc.properties文件
prop.driver=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=123456
<?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:property-placeholder location="classpath:jdbc.properties"/>

        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <!-- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                set方法注入
            -->
            <!-- 获取properties文件内容,根据key获取,使用spring表达式获取 -->
            <property name="driverClassName" value="${prop.driver}"></property>
            <property name="url" value="${prop.url}"></property>
            <property name="username" value="${prop.userName}"></property>
            <property name="password" value="${prop.password}"></property>
        </bean>

</beans>

(2)基于注解(常用)

什么是注解
  1. 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
  2. 使用注解,注解作用在类上面,方法上面,属性上面
  3. 使用注解目的:简化xml配置
Spring提供的注解

需要导入:spring-aop的jar包

  • @Component:把普通pojo实例化到spring容器中
  • @Service: 服务层(注入DAO)
  • @Controller: 控制层(注入服务)
  • @Repository :实现DAO
    上面四个注解功能是一样的,都可以用来创建bean实例(但有约定,一般怎么使用)

先开启扫描(扫描相应包的注解):一般有两种方式。

<!--配置xml文件进行扫描-->
<!--
开启组件扫描 
1 如果扫描多个包,多个包使用逗号隔开 
2 扫描包上层目录 
-->

<!--use-default-filters="false" 表示现在不使用默认filter,自己配置filter 
context:include-filter ,设置扫描哪些内容 
context:exclude-filter: 设置哪些内容不进行扫描
-->
    <context:component-scan base-package="com.dxs" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
//使用注解和类配置扫描
//完全替代了xml配置文件
@Configuration
@ComponentScan(basePackages = {
    
    "com.dxs"})
public class SpringConfig {
    
    }

类示例:

@Service
public interface UserDao {
    
    
    void add();
}
@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao {
    
    
    @Override
    public void add() {
    
    
        System.out.println("service add");
    }
}

//在注解里面value属性值可以省略不写
//默认值是类名称,首字母小写
@Component(value = "userService")
public class UserService {
    
    

//    @Autowired(根据属性类型进行自动装配,即去寻找UserDao的实现类)
//但如果有多个实现类,可以通过@Qualifier,根据名称注入
//    @Qualifier(value = "userDaoImpl1")
//@Qualifier:根据名称进行注入,和@Autowired一起使用
//    private UserDao userDao;


//@Resource:可以根据类型注入,可以根据名称注入
    @Resource(name = "userDaoImpl1")
    private UserDao userDao;


//@Value:注入普通类型属性
    @Value(value = "abc")
    private String name;

    @Value(value = "1")
    private int x;

    public void add(){
    
    
        System.out.println("UserService");
        userDao.add();
        System.out.println(name);
        System.out.println(x);
    }
}
@Test
    public void test2(){
    
    
        ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

四、AOP

1.AOP概念

面向切面编程(方面),利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

通俗描述:不通过修改源代码方式,在主干功能里面添加新功能

例如(登录):
将判断逻辑独立出来,需要时进行引用,从而降低耦合度。
在这里插入图片描述

2.AOP底层原理

底层原理:动态代理
两种动态代理:

  1. 有接口情况,使用JDK动态代理
  2. 没有接口情况,使用CGLIB动态代理

具体:Java设计模式之代理模式

3.AOP术语

  • 连接点:类里面可以被增强的方法,称为连接点
  • 切入点:实际被增强的方法,成为切入点
  • 通知(增强):实际增强的逻辑部分(有前置通知、后置通知、环绕通知、异常通知、最终通知)
  • 切面:是动作,把通知应用到切入点的过程

4.AOP操作

Spring框架一般都是基于AspectJ实现AOP操作。

AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spirng框架一起使用,进行AOP操作

需要引入AOP相关依赖

(0)切入点表达式

切入点表达式作用:知道对哪个类里面的哪个方法进行增强

语法结构: execution([ 权限修饰符 ] [返回类型] [类全路径] [方法名称] ([参数列表]) )

权限修饰符可以省略
返回类型:可以用 * 表示
如果想批量操作,可以用 * 表示。如:execution( * com.dxs.dao.BookDao.* (…))

(1)基于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: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 https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="book" class="com.dxs.spring5.aopanno.Book"></bean>
    <bean id="bookProxy" class="com.dxs.spring5.aopanno.BookProxy"></bean>

    <aop:config>
    <!--设置切入点-->
        <aop:pointcut id="p" expression="execution(* com.dxs.spring5.aopanno.Book.buy(..))"/>

	 <!--设置切面-->
        <aop:aspect ref="bookProxy">

			<!--增强-->
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>
//被增强
public class Book {
    
    
    public void buy(){
    
    
        System.out.println("buy");
    }
}
public class BookProxy {
    
    
	//前置通知
    public void before(){
    
    
        System.out.println("before");
    }

}
@Test
    public void test2(){
    
    
        ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");
        User user = context.getBean("book", User.class);
        user.add();
    }

(2)基于注解实现

@Configuration 
@ComponentScan(basePackages = {
    
    "com.atguigu"}) @EnableAspectJAutoProxy(proxyTargetClass = true) 
//配置AOP,自动注入注解
public class ConfigAop {
    
     }
//被增强
@Component
public class User {
    
    

    public void add(){
    
    
        System.out.println("ADD");
    }
}
//@Aspect:表示切面
//@Order:表示优先级,如果对同一个切入点增强,可以通过设置优先级来设置执行顺序,值越小优先级越高
@Component
@Aspect
@Order(value = 3)
public class UserProxy {
    
    

    @Pointcut(value = "execution(* com.dxs.spring5.aopanno.User.add())")
    public void pointCut(){
    
     }

//前置通知
    @Before(value = "pointCut()")
    public void  before(){
    
    
        System.out.println("before");
    }

//最终通知
    @After(value = "execution(* com.dxs.spring5.aopanno.User.add())")
    public void  after(){
    
    
        System.out.println("after");
    }

//后置通知(返回通知)
    @AfterReturning(value = "execution(* com.dxs.spring5.aopanno.User.add())")
    public void  afterReturning(){
    
    
        System.out.println("afterReturning");
    }

//异常通知
@AfterThrowing(value = "execution(* com.dxs.spring5.aopanno.User.add())")
    public void  afterThrowing(){
    
    
        System.out.println("afterThrowing");
    }

//环绕通知
    @Around(value = "execution(* com.dxs.spring5.aopanno.User.add())")
    public void  around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
    
    
        System.out.println("around before");

		//被增强方法执行
        proceedingJoinPoint.proceed();

        System.out.println("around after");
    }

}

结果:

around before
before
ADD
afterReturning
after
around after

猜你喜欢

转载自blog.csdn.net/weixin_44759105/article/details/113143037