学习背景
地点:长沙欧富安科技园1栋5楼飞思项目十
时间:23年9月4~9月8号
大致内容:Spring-framework
前言
Spring,一个更加厉害的框架,一个拯救了java的框架,而我有幸可以被该领域内的大神传授有关Spring的知识。
Spring-framework
入门
我们这时学的是Spring-framework,其中的控制反转(依赖注入)是基础,几乎之后学习的内容都是围绕着它进行展开。而什么是控制反转?简单点来说,就是帮你省去了实例化,不需要你去new一个对象,也解决了类中嵌套其它类的情况。而它有两种开发模式,一种是传统的依赖xml文件配置,另一种是依靠注解进行开发。
开发模式
在我们创建了一个Maven项目之后,首先仍要在pom.xml中导入相关依赖
AOP
Spring.xml
在resources包下创建Spring.xml,此时存在几种依赖注入模式:
手动注入依赖
自动注入
全局注入
注解
//将该注释置于朱雷之上
@Component
Bean
bean的创建方式
【1】默认使用构造函数创建
在Spring的配置文件中使用bean标签,配置 id 和 class 属性后,没有其他属性和标签时,采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="helloworld" class="com.LSTAR.Helloworld">
【2】类中的方法创建
很多时候我们会使用某个类中的或者jar包中的方法或者普通工厂中的方法来创建对象,并存入到Spring容器中
<bean id="school" class="com.LSTAR.School"></bean>
<bean id="helloworld" factory-bean="school" factory-method="getHelloworld"></bean>
【3】类中的静态方法创建
使用某个类中的静态方法创建或者工厂中的或者jar包中的静态方法创建,并存入到Spring容器中
<bean id="school" class="com.LSTAR.School"></bean>
<bean id="helloworld" class="com.LSTAR.School" factory-method="getHelloworld"></bean>
bean的获取方式
配置文件就是让IOC容器能够来管理一个具体的对象,主要就是通过配置<bean>进行管理,Spring 能够通过获取<bean>的配置来获取到对应的对象以及属性,<bean>中 id 表示唯一属性,class 表示类的全类名,通过反射的方式创建对象:
Class class = Class.forName("com.LSTAR.Helloworld");
Object obj = class.=newlnstance(); //无参构造函数
bean的获取有三种方式
【1】根据 id 获取
通过唯一标识 id 来获取,上面的环境搭建就是用的这种方式
Helloworld hello = (Helloworld) ioc.getBean("helloworld");
【2】通过 bean 类型获取
如果同一个类型的bean在xml文件中配置了多个,则获取时会抛出异常,所以同一个类型的bean在容器中必须是唯一的
Helloworld hello = ioc.getBean(Helloworld.class);
【3】指定bean的 id 值和类型
Helloworld hello = ioc.getBean("helloworld",Helloworld.class);
bean对象的生命周期
【1】单例对象
出生:当容器创建的时候bean对象出生
活着:只要容器还在,bean对象就一直活着
死亡:容器销毁,bean对象就消亡
单例bean对象随容器共存亡
【2】多例对象
出生:当使用对象时,Spring创建对象
活着:对象只要在使用过程中就一直活着
死亡:当对象长时间不用且没有其他对象引用时,有Java垃圾回收器回收
bean的作用范围
通过bean 标签的 scope 属性来指定 bean 的作用范围,属性值有:
singleton:单例的(默认值)
prototype:多例的
request:作用于 web 应用的请求范围
session:作用于 web 应用的会话范围
global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,就是session
AOP面向切面编程
使用注解@Aspect创建切面
@Aspect
public class Audience {
//"execution(* 指定类的全限定包名(..))"
@Before("execution(* concert.Performance.perform(..))")
public void silenceCellPhones() {
System.out.println("通知方法会在目标方法调用之前执行
");
}
@After("execution(* concert.Performance.perform(..))")
public void silenceCellPhones() {
System.out.println("通知方法会在目标方法返回或抛出异常后调用
");
}
@AfterReturning("execution(* concert.Performance.perform(..))")
public void applause() {
System.out.println("通知方法会在目标方法返回后调用
");
}
@AfterThrowing("execution(* concert.Performance.perform(..))")
public void demandRefund() {
System.out.println("通知方法会在目标方法抛出异常后调用
");
}
}
需要通过@EnableAspectJAutoProxy注解启动自动代理功能,这样切面就会被织入到Spring管理的bean中。
@Configuration
@ComponentScan
@EnableAspectJAutoProxy // 启用自动代理
public class ConcertConfig {
@Bean
public Audience audience() {
return new Audience();
}
@Bean
public Performance singer() {
return new Singer();
}
}
总结
长帆破浪会有时 直挂云帆济沧海