Spring简介
Spring设计理念
- 是面向Bean的编程
Spring两大核心技术
- 控制反转(IoC:Inversion of Control)/依赖注入(DI:Dependency Injection)
- 面向切面编程(AOP:Aspect Oriented Programming)
1、控制反转———创建对象的控制权转移,是一种程序设计思想
2、依赖注入———将依赖的对象注入到需要的类中去,是"控制反转"设计思想的具体实现方式
3、面向切面编程(AOP)———将复杂的需求分解出不同方面,将不同对象、不同模块之间的共同业务集中解决。通过动态代理的方式,把抽离出来的共性代码"织入"到业务代码中,实现对原有代码的增强处理。
SpringAOP中常用的术语:
Joinpoint(连接点):所谓连接点是指那些被拦截到的点,在Spring中这些点指的是方法,
因为Spring只支持方法类型的连接点。
Pointcut(切入点):是指我们要对那些Joinpoint进行拦截的定义。
Advice(通知/增强):通知是指拦截到Joinpoint之后要做的事情就是通知,通知的类型
有:前置通知、后置通知、异常通知、最终通知、环绕通知。
Introduction(引介):是一种特殊的通知在不修改类代码的前提下,Introduction可以在
运行期为类动态的添加一些方法或属性
Target(目标对象):代理的目标对象
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程
Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
Aspect(切面):是切入点和通知(引介)的结合。
Spring的应用
1、在pom.xml中下载并导入所需的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.24</version>
</dependency>
这里我用的是Junit做的测试
<!--测试jar包-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
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
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
3、创建实体类
创建一个简单的HelloWorld类
public class Helloworld {
private String name;
public Helloworld(){
System.out.println("创建对象");
}
public void setName(String name) {
System.out.println("调用方法");
this.name = name;
}
public void sayHello(){
System.out.println("Hello!" + name);
}
}
4、对类进行配置
配置之后如下
<?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">
<!--配置bean
id属性:给当前bean起一个名称,该名称必须保证是唯一的
class属性:设置bean的全类名-->
<bean id="helloworld" class="com.LSTAR.Helloworld">
<!--给属性赋值
name属性:设置bean属性名
value属性:设置bean属性值-->
<property name="name" value="LSTAR"></property>
</bean>
</beans>
5、测试类
public class test {
@Test
public void test(){
//1.创建IOC容器对象
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取Helloworld对象
Helloworld hello = (Helloworld) ioc.getBean("helloworld");
//3.调用类中方法
hello.sayHello();
}
}