Spring框架

Spring

Spring框架是Java开发领域极为著名且功能强大的一个框架。如今,众多应用都围绕Spring进行开发,使其成为每位Java开发者必须掌握的核心技能。随着Spring的不断发展,其内涵也经历了相应的演变与扩展,但在这里,我们特指Spring Framework这一核心框架。

引入

使用Maven引入Spring依赖

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.39</version>
</dependency>

使用java类进行配置

新建一个java文件,写入

1
2
3
4
@Configuration    //声明这是配置文件
@ComponentScan //提示Spring框架去扫描项目中带有@Component注解的组件(方法,类,成员等)
public class SpringConfig {
}

注入

注入是Spring框架中的基本操作之一,它是指对象的依赖关系(即它需要协作的其他对象)由外部容器(Spring IoC 容器)在运行期动态地注入,而不是由对象自身在内部直接创建。

详细一点,请看下面的演示

创建文件ProductionService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package Spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component //声明注解,只有加了这个注解才能被Spring扫描到
public class ProductService implements ProductionService{
public String GetProduction(Long product_id)
{


return " "+product_id ;
}
}

创建文件OrderService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package Spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component //声明注解,只有加了这个注解才能被Spring扫描到
public class OrderService implements getorder {
@Autowired //这里是注入点
ProductionService productionService ;


public String Getorder (Long order_id)
{

String product = productionService.GetProduction(10010L);
return "你的订单是 "+ order_id + "你的产品是"+product;
}
}

如果没有Spring,我们想要调用get_order服务,那么我们就需要在代码中new一个类为ProductService的对象才能使用他的方法,这在大型项目开发中具有很高的耦合度并且很麻烦。但是如果使用Spring来调用,如下:

创建文件SpringDemo.java

1
2
3
4
5
6
7
8
9
10
11
package Spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
OrderService orderService = context.getBean(OrderService.class); //Spring容器开始查找并管理OrderSeervice类的对象
String order = orderService.Getorder(9999L);
System.out.println(order);
}

运行, 就会发现我们无需手动创建ProductService对象,就能直接使用其方法。

所以,注入这一基本操作我们只需要记住两个注解就可以了。

1
2
3
4
@Component
声明一个组件
@Autowired
注入

IOC与DI

IOC,全称Inversion of Control,中文译为控制反转。在传统的编程模式中,对象之间的创建、组装和管理都是由开发人员手动完成的。而在IOC模式下,这些责任被委托给一个容器(如Spring容器)来管理。这意味着对象不再自行创建和管理其依赖对象,而是由容器在运行时动态地创建和注入这些依赖对象。控制权从代码反转到了容器。从对象内部控制反转到了外部容器控制。

我们上面的例子就是,将本来的开发者创建并管理类变量的工作转变为了容器来承担。

DI,(Dependency Injection,依赖注入)是一种实现控制反转(IoC)的设计模式,可以说是一种特殊的IOC。

依赖:对象a里面需要用到对象b、对象c。可以说对象a依赖对象b、对象c。

注入:把对象b、对象c放到对象a的过程叫做注入。

在上面的例子中,我们的获取订单服务,需要用到商品服务,那么就是订单服务依赖于商品服务。