spring官方文档浅翻译(1)

news2024/9/17 7:31:49

文章目录

  • IOC容器
    • IOC容器和beans的介绍
      • 实例化 Bean
      • BeanFactory:
      • ApplicationContext
    • 容器概述
      • 配置元数据
      • 实例化容器
      • 组合基于xml的配置元数据
      • 使用容器
    • bean的概述
      • 命名bean
        • 别名的使用
      • 实例化bean
        • 构造函数实例化
        • 静态工厂实例化
        • 实例工厂方法
        • bean 在运行时的实际类型
    • 依赖
      • 依赖注入

IOC容器

IOC容器和beans的介绍

IOC 容器是 Spring 框架的核心部分之一,它负责管理和维护应用程序中的对象(beans)
“Inversion of Control” 指的是将对象的创建、组装和依赖关系的管理权从应用程序代码转移到框架中

实例化 Bean

IOC 容器有两种主要的实现:

BeanFactory:

这是 Spring 最基本的容器,提供了最简单的 bean 容器功能。它延迟初始化 beans,即只有在请求时才会实际创建和初始化 bean。这对于资源消耗较大的 bean 非常有用。

ApplicationContext

这是 BeanFactory 的子接口,提供了更多的功能,如国际化支持、事件传播、AOP 功能等。ApplicationContext 在启动时会预先实例化和初始化 beans,以便在应用程序运行期间能够更快地访问和使用它们

容器概述

高水平概括
在这里插入图片描述

配置元数据

XML 配置文件:

<bean id="userService" class="com.example.UserService">
    <property name="userRepository" ref="userRepository" />
</bean>

注解
使用 @Component 注解将一个类标记为一个 Spring bean:

@Component
public class UserService {
    // ...
}

Java 配置类:

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}

实例化容器

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- services -->

    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>

组合基于xml的配置元数据

模块化配置:
可以将不同的模块分开定义在不同的 XML 文件中。每个模块可以有自己的配置文件,其中定义了与该模块相关的 beans 和依赖关系。然后,在主配置文件中通过 元素引入这些模块的配置文件
所有位置路径都相对于执行导入的定义文件,

<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">

    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    前导斜杠会被忽略。然而,考虑到这些路径是相对的,最好不要使用斜杠
    <import resource="/resources/themeSource.xml"/>

    <!-- Define additional beans or configurations -->
</beans>

Profile 切换:
你可以使用 Spring 的 Profile 功能,在不同的环境或条件下切换配置

<beans profile="development">
    <!-- Define beans and configurations for development environment -->
</beans>

<beans profile="production">
    <!-- Define beans and configurations for production environment -->
</beans>

使用容器

意味着在 Spring 框架中如何使用容器来管理和组织你的应用程序的组件

  1. 定义 Beans:
  2. 获取 Beans:
//1
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);

//2
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
//petStore是xml文件中的一个id
PetStoreService service = context.getBean("petStore", PetStoreService.class);
List<String> userList = service.getUsernameList();


//3
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
  1. 依赖注入:Spring 容器负责处理 beans 之间的依赖关系。你可以通过构造函数注入、setter 方法注入或字段注入等方式
  2. 生命周期管理:

bean的概述

在这里插入图片描述

命名bean

确保 bean 的名称是唯一的,以便在容器中准确引用

  1. xml
    Bean 的名称用于在**容器中引用、获取和识别 beans。**可以通过多种方式指定 bean 的名称
id一定是唯一的
<bean id="userService" class="com.example.UserService" />


name 属性可以指定多个名称,使用逗号或分号分隔。
<bean name="userBean,userService" class="com.example.UserService" />

  1. java:
    可以使用 @Component 注解来为 bean 分配一个默认名称,该名称是类名的小写字母开头的形式。

@Component
public class UserService {
    // ...
}


使用 Qualifier 注解:
@Autowired
@Qualifier("userService")
private UserService userService;


使用 Java 配置类:
@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}

别名的使用

  1. xml
<bean id="userService" class="com.example.UserService" />
<alias name="userService" alias="userManagementService" />

引用别名
<bean id="anotherBean" class="com.example.AnotherBean">
    <property name="userService" ref="userManagementService" />
</bean>

2.AliasFor
这要求使用 @AliasFor 注解的类和 bean 必须具有相同的注解类型

@AliasFor("userService")
@Component("userManagementService")
public class UserManagementService {
    // ...
}

实例化bean

构造函数实例化

通过调用类的构造函数来完成的

 你可以使用 <constructor-arg> 元素来指定构造函数的参数值
<bean id="user" class="com.example.User">
   <constructor-arg value="John" />
   <constructor-arg value="Doe" />
</bean>

静态工厂实例化

public class UserFactory {
   private UserFactory() {
       // private constructor to prevent direct instantiation
   }

   public static User createUser(String firstName, String lastName) {
       return new User(firstName, lastName);
   }
}

指定工厂类

<bean id="user" class="com.example.UserFactory" factory-method="createUser">
这是值
   <constructor-arg value="John" />
   <constructor-arg value="Doe" />
</bean>

实例工厂方法

public class UserFactory {
    public User createUser(String firstName, String lastName) {
        return new User(firstName, lastName);
    }
}

指定

<bean id="userFactory" class="com.example.UserFactory" />

<bean id="user" factory-bean="userFactory" factory-method="createUser">
    <constructor-arg value="John" />
    <constructor-arg value="Doe" />
</bean>

bean 在运行时的实际类型

Bean 类型和代理:用bean类型的和代理的类型
getClass() 方法:返回对象的实际运行时类,要注意,如果有代理存在,这个方法返回的可能是代理类的类型。
AopProxyUtils.ultimateTargetClass() 方法:这个方法会遍历代理链,找到最终的目标类。
目的:你可能需要了解对象的实际类型,特别是在处理代理、动态代理、AOP 等情况时。这有助于你更好地理解对象的行为和工作原理

依赖

依赖注入

Spring 框架的核心概念之一,它用于管理和注入对象之间的依赖关系。依赖注入的目的是降低组件之间的耦合度

  1. 构造函数
@Component
public class UserService {
    private UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // ...



package examples;

public class ExampleBean {

    // Fields omitted

    @ConstructorProperties({"years", "ultimateAnswer"})
    public ExampleBean(int years, String ultimateAnswer) {
        this.years = years;
        this.ultimateAnswer = ultimateAnswer;
   

使用xml

public class ThingOne {

    public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {
        // ...
    }
}


}
<beans>
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>

    <bean id="beanTwo" class="x.y.ThingTwo"/>

    <bean id="beanThree" class="x.y.ThingThree"/>
</beans>

也可以指定类型
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>

指定index
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>

指定名字
<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>
  1. Setter 方法注入
@Component
public class UserService {
    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // ...
}
setter与constructor

因此对于**强制依赖项使用构造函数**,而对于**可选依赖项使用setter方法**或配置方法是一条很好的经验法则。**注意,在setter方法上使用@Required注释可以使属性成为required依赖项**
  1. 字段注入
@Component
public class UserService {

    @Autowired
    private UserRepository userRepository;

    // ...
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/888855.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

学习笔记|基于Delay实现的LED闪烁|模块化编程|SOS求救灯光|STC32G单片机视频开发教程(冲哥)|第八集:实现LED闪烁(下)

文章目录 2 函数的使用1.函数定义&#xff08;需要带类型&#xff09;2.函数声明&#xff08;需要带类型&#xff09;3.函数调用 3 新建文件&#xff0c;使用模块化编程新建xxx.c和xxx.h文件xxx.h格式&#xff1a;调用头文件验证代码调用&#xff1a;完整的文件结构如下&#x…

使用 RHEL 系统角色

使用 RHEL 系统角色 安装 RHEL 系统角色软件包&#xff0c;并创建符合以下条件的 playbook /home/curtis/ansible/selinux.yml &#xff1a; 在所有受管节点上运行 使用 selinux 角色 将角色配置为以强制执行状态使用SELinux yum install rhel-system-roles.noarch su - curti…

七夕送礼指南:这几款礼物不仅颜值高而且非常实用

七夕又被称为“乞巧节”&#xff0c;相传这一天是牛郎织女一年一度的相会日&#xff0c;所以在这个浪漫的节日里&#xff0c;很有多的恋人也会不远万里来相见&#xff0c;在这个浪漫的日子里&#xff0c;送礼物是表达心意和爱意的重要方式&#xff0c;那么&#xff0c;面对琳琅…

前端练手小项目--自定义时间(html+css+js)

自定义时间 写文章的因 关于要写这篇文章的原因 是记录在工作上遇到的困难需求&#xff0c;是希望能给大家提供一些解决问题的思路 接下来我描述这个需求的多样性&#xff0c;难点在哪。 勾选勾选框开始时间与结束时间默认显示昨天与今天。取消勾选框开始时间与结束时间清空。…

element+vue 表格行拖拽功能

解决方案 使用 sortable.js 步骤一&#xff1a; 安装 npm install vuedraggable步骤二&#xff1a;引入 import Sortable from sortablejs;步骤三&#xff1a; el-table 添加row-key属性&#xff0c;外层包一层 sortableDiv <div class"sortableDiv"> 拖…

IDEA【java.sql.SQLSyntaxErrorException: ORA-00904: “P“.“PRJ_NO“: 标识符无效】

IDEA报错如下&#xff1a; 2023-08-17 11:26:15.535 ERROR [egrant-biz,b48324d82fe23753,b48324d82fe23753,true] 24108 --- [ XNIO-1 task-1] c.i.c.l.c.RestExceptionController : 服务器异常org.springframework.jdbc.BadSqlGrammarException: ### Error queryin…

Docker 的基本概念和优势,在应用程序开发中的实际应用。

Docker是一个开源的容器化平台&#xff0c;让开发者能够轻松地打包、运输和运行应用程序。其基本概念包括&#xff1a; 镜像(Image)&#xff1a;一个镜像是一个只读的软件包&#xff0c;它包含了运行应用所需的所有代码、库文件、环境变量和配置文件等。 容器(Container)&…

docker之简介与安装

环境配置问题 没有虚拟机&#xff0c;我们往往是打包代码发给对方&#xff0c;然后让对方安装相应的环境&#xff0c;比如node、数据库&#xff0c;要是配置不同&#xff0c;项目很有可能无法运行&#xff0c;还会报错&#xff0c;如果多个人想要运行这份代码&#xff0c;那还得…

手撸一个简单的Tomcat,延伸`SpringMvc`的原理

为什么写这篇文章 一直以来都说tomcat是用的java写的&#xff0c;但是也是不明白到底是怎么弄的&#xff0c;最近有个机会搞明白了&#xff0c;特此记录&#xff0c;可以使得更懂tomcat的原理 用java写一个java的运行程序&#xff0c;听着就很酷&#xff0c;你觉得呢&#xf…

多模态分割医学数据集小调研

QaTa-COV19 V1&#xff1a; 该数据集由4603张COVID-19胸部x光片组成;该数据集首次包含了用于COVID-19感染区域分割任务的真值分割掩码。加上对照组的胸部x光片&#xff0c;QaTa-COV19由120,968张图像组成。图像位于“QaTa-COV19/ images /”文件夹下&#xff0c;ground-truth分…

selector.replaceAll is not a function报错问题

个人项目地址&#xff1a; SubTopH前端开发个人站 &#xff08;自己开发的前端功能和UI组件&#xff0c;一些有趣的小功能&#xff0c;感兴趣的伙伴可以访问&#xff0c;欢迎提出更好的想法&#xff0c;私信沟通&#xff0c;网站属于静态页面&#xff09; SubTopH前端开发个人站…

Leetcode49. 字母异位词分组

给你一个字符串数组&#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 解题思路&#xff1a;计数 思路&#xff1a;题意是字符串的字符都是小写&#xff0c;可以对每个字符串统计其中字符的…

什么是公网、私网、内网、外网?

中午好&#xff0c;我的网工朋友。 最近经常有很多小白朋友在问&#xff0c;公网、私网、内网、外网&#xff0c;这些的概念是啥样的&#xff0c;又该怎么去界定。 关于IP地址&#xff0c;确实没有太明确的区分&#xff0c;其实也不必太过咬文嚼字。 内网、外网就是一个参考…

SAP复杂表格转换为JASON格式的例子

分享一个三层表格转换伙JASON格式的例子&#xff0c;代码如下。 REPORT zjason_test. "// 定义 DATA: lv_json TYPE string.DATA: BEGIN OF ls_detail_l3,code_l3 TYPE string,name_l3 TYPE string,age_l3 TYPE string,END OF ls_detail_l3,lt_detail_l3 LIKE TABLE OF…

SSO单点登录(SpringSecurity OAuth2.0 redis mysql jwt)

SSO单点登录 什么是单点登录 SSO(Single Sign On) 在多系统架构中&#xff0c;用户只需要一次登录就可以无需再次登录(比如你在打开淘宝之后点击里边的天猫) 在以前我们的单系统中,用户如果登录多个服务需要多次登录&#xff0c;实现单点登录之后&#xff0c;可以实现一次登录…

Qt:隐式内存共享

隐式内存共享 Many C classes in Qt use implicit data sharing to maximize resource usage and minimize copying. Implicitly shared classes are both safe and efficient when passed as arguments, because only a pointer to the data is passed around, and the data i…

K8s实战4-使用Helm在Azure上部署Ingress-Nginx和Tokengateway

手动发布Ingress-Nginx 1 登录到aks(dfinder-gw-aks) az login az account set --subscription ${sub ID} az aks get-credentials --resource-group ${groupname} --name ${aks name} 2 下载 ingress-nginx-4.2.5.tgz curl -LO https://github.com/kubernetes/ingress-ngi…

Hyper-V增加桥接网络设置(其他方式类同)

点击连接到的服务器&#xff0c;右单击或者右边点击“虚拟交换机管理器” 选择网络种类 配置虚拟交换机信息 外部网络选择物理机网卡设备

CS1988|C#无法在异步方法中使用ref,in,out类型的参数的问题

CS1988|C#无法在异步方法中使用ref,in,out类型的参数 &#x1f300;|场景&#xff1a; BlazorServer的场景中推荐使用异步方法&#xff0c;使用ref,out,in为参数前缀则报错CS1988 原因如下: ref parameters are not supported in async methods because the method may not h…

torch模型转onnx

加载模型 modeltorch.load(saved_model/moudle_best_auc.pth, map_locationcpu) model.eval().cpu()注&#xff1a;由于导出的模型是用于推理的&#xff0c;因此必须指定模型加载的位置和模型验证的位置&#xff0c;这里我使用了cpu做出导出的硬件 分析模型的输入和输出 这里…