Spring框架(中)

1、基于注解管理Bean:

1、开启组件扫描:

        Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过 context:component-scan 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中。

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--开启组件扫描功能--><context:component-scan base-package="com.atguigu.spring6"></context:component-scan>
</beans>

        注意:在使用 context:component-scan 元素开启自动扫描功能前,首先需要在 XML 配置的一级标签 <beans> 中添加 context 相关的约束。

情况一:最基本的扫描方式

<context:component-scan base-package="com.atguigu.spring6">
</context:component-scan>

情况二:指定要排除的组件

<context:component-scan base-package="com.atguigu.spring6"><!-- context:exclude-filter标签:指定排除规则 --><!-- type:设置排除或包含的依据type="annotation",根据注解排除,expression中设置要排除的注解的全类名type="assignable",根据类型排除,expression中设置要排除的类型的全类名--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/><!--<context:exclude-filter type="assignable" expression="com.atguigu.spring6.controller.UserController"/>-->
</context:component-scan>

 情况三:仅扫描指定组件

<context:component-scan base-package="com.atguigu" use-default-filters="false"><!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 --><!-- use-default-filters属性:取值false表示关闭默认扫描规则 --><!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 --><!-- type:设置排除或包含的依据type="annotation",根据注解排除,expression中设置要排除的注解的全类名type="assignable",根据类型排除,expression中设置要排除的类型的全类名--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/><!--<context:include-filter type="assignable" expression="com.atguigu.spring6.controller.UserController"/>-->
</context:component-scan>

 2、使用注解定义 Bean

Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean。

注解说明
@Component该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可。
@Repository该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
@Service该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
@Controller该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

        实际他们的作用是一样的,只不过是我们做啦一定的规范。

测试类:

//@Component(value ="user")  //相当于 <bean id="user" class=".....">
//@Repository //不写默认就是类名首字母小写
//@Service
@Controller
public class User {
}

基于不同的注解,他们实现的功能是一样的,但是为了开发规范我们一般对于普通的类使用的是component的注解。

3、使用注解完成注入:

(1)@Autowired注入:

单独使用@Autowired注解,默认根据类型装配。【默认是byType】

 controller:

package com.songzhishu.autowired.controller;import com.songzhishu.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import java.sql.SQLOutput;/*** @BelongsProject: Spring6* @BelongsPackage: com.songzhishu.autowired* @Author: 斗痘侠* @CreateTime: 2023-10-08  16:05* @Description: TODO* @Version: 1.0*/
@Controller//创建bean对象
public class UserController {/*//第一种方式属性注入@Autowired //根据类型找到对应的对象完成注入private UserService userService;*/private UserService userService;//第二种方式 setter方法/*@Autowired  //注解写在setter方法上public void setUserService(UserService userService) {this.userService = userService;}*///第三种方式 构造器方式/* @Autowired    //基于构造器注入public UserController(UserService userService) {this.userService = userService;}*///第四种方式  形参上注入/*public UserController(@Autowired UserService userService) {this.userService = userService;}*//*//第五种 特殊情况 只有一个有参构造函数 可以不加注解public UserController(UserService userService) {this.userService = userService;}*///由@Autowired和Qualifier注解联合起来 根据名称进行匹配public UserController(UserService userService) {this.userService = userService;}public  void  add(){System.out.println("controller");userService.add();}}

 Service:(实现类)

package com.songzhishu.autowired.service;import com.songzhishu.User;
import com.songzhishu.autowired.dao.UserDao;
import com.songzhishu.autowired.dao.UserDaoImpl;
import com.songzhishu.autowired.dao.UserRedisDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;/*** @BelongsProject: Spring6* @BelongsPackage: com.songzhishu.autowired.service* @Author: 斗痘侠* @CreateTime: 2023-10-08  16:07* @Description: TODO* @Version: 1.0*/
@Service
public class UserServiceImpl  implements UserService {/*@Autowired//属性注入private UserDao userDao;*/@Autowired  //自动注入@Qualifier(value = "userRedisDaoImpl")//名字---idprivate UserDao userDao;/*@Autowired   //setterpublic void setUserDao(UserDao userDao) {this.userDao = userDao;}*//*@Autowiredpublic UserServiceImpl(UserDao userDao) {this.userDao = userDao;}*//*public UserServiceImpl(@Autowired UserDao userDao) {this.userDao = userDao;}*///当一个类型有多个bean的时候只依赖类型的话是完成不了注入的 使用两个是注解完成注入/*public UserServiceImpl(UserDao userDao) {this.userDao = userDao;}*/@Overridepublic void add() {System.out.println("service");userDao.add();}
}

 dao:

package com.songzhishu.autowired.dao;import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;/*** @BelongsProject: Spring6* @BelongsPackage: com.songzhishu.autowired.dao* @Author: 斗痘侠* @CreateTime: 2023-10-08  16:07* @Description: TODO* @Version: 1.0*/
@Repository
public class UserDaoImpl implements UserDao{@Overridepublic void add() {System.out.println("dao");}
}
package com.songzhishu.autowired.dao;import org.springframework.stereotype.Repository;/*** @BelongsProject: Spring6* @BelongsPackage: com.songzhishu.autowired.dao* @Author: 斗痘侠* @CreateTime: 2023-10-08  16:47* @Description: TODO* @Version: 1.0*/
@Repository
public class UserRedisDaoImpl implements UserDao{@Overridepublic void add() {System.out.println("redis...dao");}
}

总结

  • @Autowired注解可以出现在:属性上、构造方法上、构造方法的参数上、setter方法上。

  • 当带参数的构造方法只有一个,@Autowired注解可以省略。()

  • @Autowired注解默认根据类型注入。如果要根据名称注入的话,需要配合@Qualifier注解一起使用。(为了解决一个类型有多个bean的情况)

(2)@Resource注入:

@Resource注解也可以完成属性注入。那它和@Autowired注解有什么区别?

  • @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(JSR-250标准中制定的注解类型。JSR是Java规范提案。)

  • @Autowired注解是Spring框架自己的。

  • @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。

  • @Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。

  • @Resource注解用在属性上、setter方法上。

  • @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。

@Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。

<!-- https://mvnrepository.com/artifact/jakarta.annotation/jakarta.annotation-api -->
<dependency><groupId>jakarta.annotation</groupId><artifactId>jakarta.annotation-api</artifactId><version>2.1.1</version>
</dependency>

@Resource注解:默认byName注入,没有指定name时把属性名当做name,根据name找不到时,才会byType注入。byType注入时,某种类型的Bean只能有一个。

(3)Spring全注解开发

全注解开发就是不再使用spring配置文件了,写一个配置类来代替配置文件。

创建配置类:

package com.songzhishu.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;/*** @BelongsProject: Spring6* @BelongsPackage: com.songzhishu.config* @Author: 斗痘侠* @CreateTime: 2023-10-08  17:51* @Description: TODO* @Version: 1.0*/
//加上注解表示该类为配置类@Configuration@ComponentScan("com.songzhishu")
public class SpringConfig {}

测试类:

    @Testpublic void test4() {//加载配置类ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);UserController controller = context.getBean(UserController.class);controller.add();}

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

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

相关文章

transformer不同的包加载模型的结构不一样

AutoModel AutoModelForTokenClassification 结论&#xff1a; AutoModel加载的模型与AutoModelForTokenClassification最后一层是不一样的&#xff0c;从这个模型来看&#xff0c;AutoModelForTokenClassification加载的结果是对的 问题&#xff1a; 为什么AutoModel和Aut…

使用Docker安装JupyterHub

安装JupyterHub 拉取Jupyter镜像并运行容器 docker run -d -p 8000:8000 --name jupyterhub jupyterhub/jupyterhub jupyterhub # -d&#xff1a;后台运行 # -p 8000:8000&#xff1a;宿主机的8000端口映射容器中的8000端口 # --name jupyterhub&#xff1a;给运行的容器起名…

STL标准模板库

STL是标准模板库&#xff0c;是标准库的重要组成部分&#xff0c;将常见的数据结构以模板的方式进行封装&#xff0c;并提供一些灵活的算法 是程序员避免做大量重复性的工作而诞生出的一套标准 从广义上分为容器、算法、迭代器 容器和算法之间通过迭代器进行无缝连接,STL几乎…

单身狗

我们这题的思路就是先排序&#xff0c;然后对相邻的两个元素做比较&#xff0c;如果不相等就把前面的记录下来&#xff0c;然后往后 void bsort(int* arr, int sz) {int i 0;int j 0;for (i 0; i < sz - 1; i){for (j 0; j < sz - 1 - i; j){if (arr[j] > arr[j …

小谈设计模式(10)—原型模式

小谈设计模式&#xff08;10&#xff09;—原型模式 专栏介绍专栏地址专栏介绍 原型模式角色分类抽象原型&#xff08;Prototype&#xff09;具体原型&#xff08;Concrete Prototype&#xff09;客户端&#xff08;Client&#xff09;原型管理器&#xff08;Prototype Manager…

创建GCP service账号并管理权限

列出当前GCP项目的所有service account 我们可以用gcloud 命令 gcloud iam service-accounts list gcloud iam service-accounts list DISPLAY NAME EMAIL DISABLED terraform …

苹果手机怎么备份所有数据?2023年iPhone 15数据备份常用的3种方法!

当苹果手机需要进行刷机、恢复出厂设置、降级iOS系统等操作时&#xff0c;我们需要将自己的iPhone数据提前进行备份。 特别是在苹果发布新iOS系统时&#xff0c;总有一些小伙伴因为升降级系统&#xff0c;而导致了重要数据的丢失。 iPhone中储存着重要的照片、通讯录、文件等数…

ahk系列——ahk_v2实现win10任意界面ocr

前言&#xff1a; 不依赖外部api接口&#xff0c;界面简洁&#xff0c;翻译快速&#xff0c;操作简单&#xff0c; 有网络就能用 、还可以把ocr结果非中文翻译成中文、同样可以识别中英日韩等60多个国家语言并翻译成中文&#xff0c;十分的nice 1、所需环境 windows10及其以上…

GPU版本的Pytorch安装

GPU版本的Pytorch安装 1.CUDA的安装 查看自己计算机CUDA支持的版本 2.CUDNN的安装 对应找到CUDNN的版本 3.Pytorch的安装 找自己的CUDA对应的PYtorch安装包 https://pytorch.org/get-started/previous-versions/ 并在下面的页面下载 https://download.pytorch.org/whl/cu101/to…

【高并发】多线程和高并发提纲

文章目录 三大源头两个主要问题三大解决方案 最近正在面试&#xff0c;对多线程和高并发相关问题整理了一个提纲。 个人感觉这三大部分由底向上&#xff0c;足够展开对并发编程中大部分问题的讨论~ 三大源头 线程切换带来的原子性问题。 原子操作&#xff1a;利用CPU提供的原…

BERT相关模型不能下载问题

Author:龙箬 Computer Application Technology Change the World with Data and Artificial Intelligence ! CSDNweixin_43975035 生有热烈&#xff0c;藏与俗常 由于网络原因&#xff0c;不能下载BERT相关模型 及 tokenizer urllib3.exceptions.MaxRetryError: HTTPSConnectio…

使用Windows系统自带的安全加密解密文件操作步骤详解

原以为安全加密的方法是加密压缩包&#xff0c;有的需要用软件加密文件&#xff0c;可每次想往里面修改或存放文件都要先解密&#xff0c;不用时&#xff0c;还得去加密&#xff0c;操作步骤那么多&#xff0c;那多不方便呀&#xff0c;这里讲讲用系统自带的BitLocker加密工具怎…

强化学习------Qlearning算法

简介 Q learning 算法是一种value-based的强化学习算法&#xff0c;Q是quality的缩写&#xff0c;Q函数 Q(state&#xff0c;action)表示在状态state下执行动作action的quality&#xff0c; 也就是能获得的Q value是多少。算法的目标是最大化Q值&#xff0c;通过在状态state下…

html通过使用图像源的协议(protocol)相对 URL 来防止安全/不安全错误

有人知道使用 protocol relative URLs 是否有问题吗&#xff1f;用于图像源以防止混合内容安全警告。 例如链接一张图片: <img src"//domain.com/img.jpg" /> 代替: <img src"http://domain.com/img.jpg" /> or <img src"https…

day10.8ubentu流水灯

流水灯 .text .global _start _start: 1.设置GPIOE寄存器的时钟使能 RCC_MP_AHB4ENSETR[4]->1 0x50000a28LDR R0,0X50000A28LDR R1,[R0] 从r0为起始地址的4字节数据取出放在R1ORR R1,R1,#(0x1<<4) 第4位设置为1STR R1,[R0] 写回2.设置PE10管脚为输出模式 G…

Android多线程学习:线程

一、概念 进程&#xff1a;系统资源分配的基本单位&#xff0c;进程之间相互独立&#xff0c;不能直接访问其他进程的地址空间。 线程&#xff1a;CPU调度的基本单位&#xff0c;线程之间共享所在进程的资源&#xff0c;包括共享内存&#xff0c;公有数据&#xff0c;全局变量…

10.8c++作业

#include <iostream>using namespace std; class Rect {int width; //宽int height; //高 public://初始化函数void init(int w,int h){widthw;heighth;}//更改宽度void set_w(int w){widthw;}//更改高度void set_h(int h){heighth;}//输出矩形周长和面积void show(){co…

ASO优化之应用程序图标的设计技巧

用户在App Store页面上&#xff0c;首先看到的是我们的移动应用程序图标&#xff0c;所以应用图标的设计至关重要。如果这不能引起用户的注意&#xff0c;他们可能不会费心去了解有关我们的应用的更多信息。 1、脱颖而出的重要性。 具有附加价值&#xff0c;如果做得好&#x…

bigemap在林业勘测规划设计行业的一些应用

选择Bigemap的原因&#xff1a; 主要注重影像的时效性&#xff0c;软件的影像时效性比其他的更新快&#xff0c;更清晰。 使用场景&#xff1a; 1.林业督查&#xff0c;主要是根据国家下发的图斑&#xff0c;结合测绘局的影像以及bigemap的较新影像对比去年和今年的林地变化。…

MySQL——使用mysqldump备份与恢复数据

目录 1.mysqldump简介 2.mysqldump备份数据 2.1 备份所有数据库 2.2 备份一个/多个数据库 2.3 备份指定库中的指定表 3.mysqldump恢复数据 3.1 恢复数据库 3.2 恢复数据表 1.mysqldump简介 mysqldump命令可以将数据库中指定或所有的库、表导出为SQL脚本。表的结构和表中…