基于注解配置bean

news/2024/9/20 4:00:41/ 标签: spring, java, bean, 注解, 框架

文章目录

    • 1.基本使用
        • 1.基本介绍
        • 2.快速入门
          • 1.引入jar包
          • 2.MyComponent.java
          • 3.UserAction.java
          • 3.UserDao.java
          • 4.UserService.java
          • 5.beans05.xml
          • 6.断点查看bean对象是否创建
          • 7.测试
        • 3.注意事项和细节
    • 2.自己实现spring注解
        • 1.需求分析
        • 2.思路分析图
        • 3.编写自定义注解ComponentScan
        • 4.编写配置类SunSpringConfig
        • 5.编写容器SunSpringApplicationContext
        • 6.测试
    • 3.自动装配
        • 1.AutoWired方式
          • 1.基本说明
          • 2.UserDao.java
          • 3.UserService.java
          • 4.测试
        • 2.Resource方式(推荐)
          • 1.基本说明
          • 2.UserDao.java
          • 3.UserService.java
    • 4.泛型依赖注入
        • 1.基本说明
          • 1.基本介绍
          • 2.参考关系图

1.基本使用

1.基本介绍

image-20240219101916177

2.快速入门
1.引入jar包

image-20240219102154951

java_14">2.MyComponent.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Component;/*** @Component 标识该类是一个组件,当不确定该类的层级的时候就使用这个注解* @author 孙显圣* @version 1.0*/@Component
public class MyComponent {
}
java_33">3.UserAction.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Controller;/*** @Controller 用于标识该类是一个控制器(相当于servlet)* @author 孙显圣* @version 1.0*/
@Controller
public class UserAction {
}
java_51">3.UserDao.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Repository;/*** @Repository 用来标识该类是一个dao* @author 孙显圣* @version 1.0*/
@Repository
public class UserDao {
}
java_69">4.UserService.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Service;/*** @Service 用于标识该类是一个Service* @author 孙显圣* @version 1.0*/
@Service
public class UserService {
}
beans05xml_87">5.beans05.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--component-scan 表示对指定包下的类进行扫描,并创建对象到容器base-package 指定要扫描的包--><context:component-scan base-package="com.sxs.spring.component"></context:component-scan>
</beans>
bean_103">6.断点查看bean对象是否创建

image-20240219104840942

7.测试
java">    //通过注解来配置bean@Testpublic void setBeanByAnnotation() {//从类路径下读取配置文件ApplicationContext ioc = new ClassPathXmlApplicationContext("beans05.xml");//分别获取这四个对象,由于是单例的所以可以直接通过类型获取MyComponent component = ioc.getBean(MyComponent.class);UserAction action = ioc.getBean(UserAction.class);UserDao userDao = ioc.getBean(UserDao.class);UserService userService = ioc.getBean(UserService.class);System.out.println("" + component + action + userDao + userService);}

image-20240219105551384

3.注意事项和细节

image-20240219105946438

image-20240219133850259

image-20240219133918902

image-20240219134100805

image-20240219134942963

spring_138">2.自己实现spring注解

1.需求分析

image-20240219135303466

image-20240219135325093

2.思路分析图

image-20240219140946226

3.编写自定义注解ComponentScan
java">package com.sxs.spring.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 自定义注解:用于指定要扫描的包** @author 孙显圣* @version 1.0*/
@Target(ElementType.TYPE) //指定目前的注解可以修饰TYPE程序元素
@Retention(RetentionPolicy.RUNTIME) //指定注解的保留范围,在运行时可以生效
public @interface ComponentScan {String value() default ""; //指定注解可以传入一个String类型的值,用于指定要扫描的包
}
4.编写配置类SunSpringConfig
java">package com.sxs.spring.annotation;/*** @author 孙显圣* @version 1.0*/
@ComponentScan(value = "com.sxs.spring.component") //自定义注解:指定要扫描的包
public class SunSpringConfig {}
5.编写容器SunSpringApplicationContext
java">package com.sxs.spring.annotation;import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;import java.io.File;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;/*** 类似于Spring原生的ioc容器** @author 孙显圣* @version 1.0*/
public class SunSpringApplicationContext {//传进来一个配置类的Class对象private Class configClass;//存放对象的容器private final ConcurrentHashMap<String, Object> ioc = new ConcurrentHashMap<>();//构造器,接收配置类的class对象public SunSpringApplicationContext(Class configClass) throws ClassNotFoundException, InstantiationException, IllegalAccessException {this.configClass = configClass;//获取要扫描的包//1.首先反射获取类的注解信息ComponentScan componentScan = (ComponentScan) this.configClass.getDeclaredAnnotation(ComponentScan.class);//2.通过注解来获取要扫描的包的路径String path = componentScan.value();//得到要扫描包的.class文件//1.获取类加载器ClassLoader classLoader = SunSpringApplicationContext.class.getClassLoader();//2.获取要扫描包的真实路径,默认刚开始在根目录下path = path.replace(".", "/");URL resource = classLoader.getResource(path);//3.由该路径创建一个文件对象,可使用resource.getFile()将URL类型转化为String类型File file = new File(resource.getFile());//4.遍历该文件夹下的所有.class文件if (file.isDirectory()) {File[] files = file.listFiles();for (File f : files ) {//反射注入容器//1.获取所有文件的全路径String absolutePath = f.getAbsolutePath();//只处理class文件if (absolutePath.endsWith(".class")) {//2.分割出类名String className = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.indexOf("."));//3.得到全路径String fullPath = path.replace("/", ".") + "." + className;//4.类加载器获取Class对象(也可以通过Class.forName,区别是后者会使类被静态初始化),判断是否有那四个注解Class<?> aClass = classLoader.loadClass(fullPath);if (aClass.isAnnotationPresent(Component.class) || aClass.isAnnotationPresent(Controller.class)|| aClass.isAnnotationPresent(Service.class) || aClass.isAnnotationPresent(Repository.class)) {//5.反射对象并放入到容器中Class<?> clazz = Class.forName(fullPath);Object o = clazz.newInstance();//默认是类名首字母小写作为keyioc.put(StringUtils.uncapitalize(className), o);}}}System.out.println("ok");}}//返回容器中的对象public Object getBean(String name) {return ioc.get(name);}}
6.测试
java">package com.sxs.spring.annotation;import org.junit.jupiter.api.Test;/*** @author 孙显圣* @version 1.0*/
public class test {@Testpublic void SunSpringApplicationContextTest() throws ClassNotFoundException, InstantiationException, IllegalAccessException {SunSpringApplicationContext ioc = new SunSpringApplicationContext(SunSpringConfig.class);Object myComponent = ioc.getBean("myComponent");Object userAction = ioc.getBean("userAction");Object userDao = ioc.getBean("userDao");Object userService = ioc.getBean("userService");System.out.println("" + myComponent + userService + userAction + userDao);}
}

image-20240219160545576

3.自动装配

1.AutoWired方式
1.基本说明

image-20240219172851649

java_306">2.UserDao.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Repository;/*** @Repository 用来标识该类是一个dao* @author 孙显圣* @version 1.0*/
@Repository
public class UserDao {public void sayHi() {System.out.println("hi");}
}
java_327">3.UserService.java
java">package com.sxs.spring.component;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @Service 用于标识该类是一个Service* @author 孙显圣* @version 1.0*/
@Service
public class UserService {//自动装配//1.通过UserDao这个类型来匹配,如果有多个实例,则使用第二种方式匹配//2.通过userDao这个属性名字作为id匹配实例,如果还是匹配不到则报错@AutowiredUserDao userDao;public void sayHi() {userDao.sayHi();}
}
4.测试
java">    //测试@autowire自动装配@Testpublic void autowireTest() {//获取容器ApplicationContext ioc = new ClassPathXmlApplicationContext("beans05.xml");UserService bean = ioc.getBean("userService", UserService.class);bean.sayHi();}

image-20240219173043506

2.Resource方式(推荐)
1.基本说明

image-20240219173244707

java_376">2.UserDao.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Repository;/*** @Repository 用来标识该类是一个dao* @author 孙显圣* @version 1.0*/
@Repository
public class UserDao {public void sayHi() {System.out.println("hi");}
}
java_397">3.UserService.java
java">package com.sxs.spring.component;import org.springframework.stereotype.Service;import javax.annotation.Resource;/*** @Service 用于标识该类是一个Service* @author 孙显圣* @version 1.0*/
@Service
public class UserService {//自动装配//1.通过name匹配:直接根据注解的属性name来进行匹配,如果匹配不到直接报错//2.通过类型匹配:必须保证是单例的,如果有多个实例,则直接报错//3.默认:先通过name属性匹配,如果匹配不上则按照类型匹配,都匹配不上才会报错@ResourceUserDao userDao;public void sayHi() {userDao.sayHi();}
}

4.泛型依赖注入

1.基本说明
1.基本介绍

image-20240219184142629

2.参考关系图

image-20240219185501222


http://www.ppmy.cn/news/1427080.html

相关文章

Covalent Network(CQT)宣布推出面向 Cronos 生态的捐赠计划与 API 积分,为 Web3 创新赋能

为了促进 Web3 领域的创新&#xff0c;Covalent Network&#xff08;CQT&#xff09;宣布将其捐赠计划向 Cronos 生态系统中的开发者拓展。这一战略性举措&#xff0c;旨在通过向 Cronos 网络中基于 Covalent Network&#xff08;CQT&#xff09;API 构建的项目提供支持和资源&…

有没有批量调节音乐播放速度的方法?调节音频的播放速度

一&#xff0c;引言​ 调节音乐播放的速度是一种有趣而富有创造性的方式&#xff0c;可以改变我们对音乐的感知和体验。通过调整音乐的速度&#xff0c;我们可以创造出全新的听觉效果&#xff0c;让音乐呈现出不同的情感和氛围。二&#xff0c;调节音乐速度的效果 调节音乐速…

【系统架构师】-案例考点(一)

1、软件架构设计 主要考点&#xff1a; 质量属性、软件架构风格、软件架构评估、MVC架构、面向服务的SOA架构、 DSSA、ABSD 1.1、质量属性 1、性能:指系统的响应能力&#xff0c;即要经过多长时间才能对某个事件做出响应&#xff0c;或者在某段时间内系统所能处理的事件的…

mybatis(5)参数处理+语句查询

参数处理&#xff0b;语句查询 1、简单单个参数2、Map参数3、实体类参数4、多参数5、Param注解6、语句查询6.1 返回一个实体类对象6.2 返回多个实体类对象 List<>6.3 返回一个Map对象6.4 返回多个Map对象 List<Map>6.5 返回一个大Map6.6 结果映射6.6.1 使用resultM…

PyTorch深度解析:Tensor——神经网络的核心构建块

在深度学习和神经网络的研究与应用中&#xff0c;Tensor&#xff08;张量&#xff09;无疑是一个核心概念。特别是在PyTorch这一强大的深度学习框架中&#xff0c;Tensor更是扮演了举足轻重的角色。本文将深入探讨PyTorch中的Tensor&#xff0c;从其基本定义、特性、操作到实际…

Ubuntu 部署ChatGLM3大语言模型

Ubuntu 部署ChatGLM3大语言模型 ChatGLM3 是智谱AI和清华大学 KEG 实验室联合发布的对话预训练模型。 源码&#xff1a;https://github.com/THUDM/ChatGLM3 部署步骤 1.服务器配置 Ubuntu 20.04 8核(vCPU) 32GiB 5Mbps GPU NVIDIA T4 16GB 硬盘 100GiB CUDA 版本 12.2.2/…

链表linked list: 将新节点链接到链表的末尾

// 在链表中插入新节点 // 这段代码定义了一个名为 insert 的函数&#xff0c;用于在链表中插入新节点。让我解释一下这段代码的逻辑&#xff1a; // 函数接受两个参数&#xff1a;指向链表头节点的引用 head 和要插入的新节点的值 value。 // 首先&#xff0c;它创建了一个新的…

Go: 理解 Sync.Pool 的设计

sync 包提供了一个强大且可复用的实例池&#xff0c;以减少 GC 压力。在使用该包之前&#xff0c;我们需要在使用池之前和之后对应用程序进行基准测试。这非常重要&#xff0c;因为如果不了解它内部的工作原理&#xff0c;可能会影响性能。 池的限制 我们来看一个例子以了解它…

GPT-3.5和GPT-Plus的区别

GPT-3.5和GPT-Plus都是OpenAI开发的大型语言模型,但它们之间有一些区别: GPT-3.5就是大家熟知的ChatGPT GPT-Plus 是Open AI 的更强的AI模型GPT-4版本。两者区别是&#xff1a; 模型规模:GPT-Plus是GPT-3的一个更大版本,参数量更多。而GPT-3.5是GPT-3的一个优化版本,在参数量…

7. Spring Boot 创建与使用

经过前面的六篇文章&#xff0c;Spring Framework的知识终于大致讲完了&#xff0c;但是Spring AOP还没提到&#xff0c;个人认为Spring AOP更适合放在Spring MVC之后再讲解&#xff0c;而讲解Spring MVC前先学习Spring Boot的目的也是为了在学习Spring MVC的时候直接使用Sprin…

高频九问:产品经理面试题解析

01 ▼ 需求评审时研发说需求实现不了怎么办&#xff1f; 1.站在技术的角度&#xff0c;了解无法实现的原因 2.看有哪些可以替代的方案 3.评估替代方案对项目本身的影响&#xff0c;如延迟&#xff0c;如若在可接受范围内&#xff0c;适当的妥协 02 ▼ 是否了解我们公司&a…

第六章 Unity中的基础光照

我们是如何看到这个世界的 需要考虑三种物理现象 (1)首先,光线从光源被发射出来 (2)然后,光线和场景中的物体相交:一些光线被吸收,一些光线被散射到其他方向。 (3)最后,摄像机吸收了一些光,产生了一张图像 光源 把光源当成一个没有体积的点,用 l 来表示它的…

React + 项目(从基础到实战) -- 第六期

引入ant design ui ui 组件库介绍 组件总览 - Ant Design (antgroup.com) 安装 - Material-UI (mui.com) Tailwind UI - Official Tailwind CSS Components & Templates 引入antd Ant Design of React - Ant Design 常用组件 // 引入antd 美化import { Layout } from a…

渗透测试工作任务概述

一、渗透测试工作任务介绍 渗透测试工作任务不是随便用个工具就可以完成的&#xff0c;需要了解网站业务情况&#xff0c;还需要在测试结束后给出安全加固的解决方案&#xff1b; 渗透测试与入侵工具区别&#xff1a; 渗透测试&#xff1a;出于保护系统的目的&#xff0c;更全…

N名学生的成绩已在主函数中放入一个带头节点的链表结构中,h指向链表的头节点。请编写函数fun,它的功能是:找出学生的最高分,由函数值返回。

本文收录于专栏:算法之翼 https://blog.csdn.net/weixin_52908342/category_10943144.html 订阅后本专栏全部文章可见。 本文含有题目的题干、解题思路、解题思路、解题代码、代码解析 分别包含C语言、C++、Java、Python四种语言的解法和详细解析。 题干 N名学生的成绩已在主…

C#:用 BigInteger 计算 斐波那契数列

using System.Numerics; 计算 斐波那契数列&#xff08;Fibonacci sequence&#xff09;&#xff0c;不受长整型位数限制。 编写 fibonacci.cs 如下 // C# program for Fibonacci Series // using Dynamic Programming using System; using System.Numerics;class fibona…

《综合品酒师》培训中FENDI CLUB精酿啤酒掀起品质生活新浪潮

近日&#xff0c;云仓酒庄的《综合品酒师》培训活动成功刷新了世界纪录&#xff0c;这一壮举不仅彰显了云仓酒庄在人才培养方面的专业实力&#xff0c;更以其与众不同的FENDI CLUB精酿啤酒掀起了酒水行业的新风尚。作为一名业内专业人士&#xff0c;我深入剖析了此次培训对酒水…

【web开发网页制作】html+css家乡长沙旅游网页制作(4页面附源码)

家乡长沙网页制作 涉及知识写在前面一、网页主题二、网页效果Page1、主页Page2、历史长沙Page3、著名人物Page4、留言区 三、网页架构与技术3.1 脑海构思3.2 整体布局3.3 技术说明书 四、网页源码HtmlCSS 五、源码获取5.1 获取方式 作者寄语 涉及知识 家乡长沙网页制作&#x…

使用QT与Web混合编程

使用QT开发客户端软件/桌面软件具有执行效率&&跨平台的相对优势&#xff0c;但是在网页中大量使用了Javascript等脚本语言&#xff0c;使用QT开发客户端软件避不开与web的交互&#xff0c;也就涉及到使用QT中的方法调用Javascript等方法。 我在QT6.6的版本使用中觉得qt…

44.HarmonyOS鸿蒙系统 App(ArkUI)栅格布局介绍

栅格布局是一种通用的辅助定位工具&#xff0c;对移动设备的界面设计有较好的借鉴作用。主要优势包括&#xff1a; 提供可循的规律&#xff1a;栅格布局可以为布局提供规律性的结构&#xff0c;解决多尺寸多设备的动态布局问题。通过将页面划分为等宽的列数和行数&#xff0c;…