基于注解配置bean

devtools/2024/9/20 4:01:21/ 标签: 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/devtools/5319.html

相关文章

Spring Boot - 利用MDC(Mapped Diagnostic Context)实现轻量级同步/异步日志追踪

文章目录 Pre什么是MDC&#xff08;Mapped Diagnostic Context&#xff09;Slf4j 和 MDC基础工程工程结构POMlogback-spring.xmlapplication.yml同步方式方式一&#xff1a; 拦截器自定义日志拦截器添加拦截器 方式二&#xff1a; 自定义注解 AOP自定义注解 TraceLog切面 测试…

功能测试_验证新浪邮箱登录的正确性

案例&#xff1a;验证验证新浪邮箱登录的正确性 功能测试_等价类设计用例&#xff1a; 步骤&#xff1a; 1:明确需求&#xff1a;邮箱能否登录 2:划分等价类&#xff1a;有效等价类、有效取值、无效等价类、无效取值 3&#xff1a;提取数据编写用例&#xff1a;用例编号、…

webpack源码分析——enhanced-resolve库之getType、normalize、join和cachedJoin函数

一、PathType 路径类型 const PathType Object.freeze({Empty: 0, // 空Normal: 1, // 默认值Relative: 2, // 相对路径AbsoluteWin: 3, // win 下的绝对路径AbsolutePosix: 4, // posix 下的绝对路径Internal: 5 // enhanced-resolve 内部自定义的一种类型&#xff0c;具体是…

正则表达式

一. 特殊符号的含义 量词 *&#xff1a;表示前面的模式零次或多次&#xff1a;表示前面的模式一次或多次?&#xff1a;表示前面的模式零次或一次{n}&#xff1a;表示前面的模式恰好 n 次{n,}&#xff1a;表示前面的模式至少 n 次{n,m}&#xff1a;表示前面的模式至少 n 次且不…

5G网络架构;6G网络架构

目录 5G和6G架构 6G网络架构 5G和6G架构 在设计和功能上有显著的区别,这主要体现在它们各自的核心特点、优势和应用场景上。 5G技术架构的核心特点包括高速率与低延迟、大容量与高密度以及网络切片。高速率与低延迟极大地提升了用户体验,支持更多实时应用和大规模数据传输…

XiaodiSec day013 Learn Note 小迪渗透学习笔记

XiaodiSec day013 Learn Note 小迪渗透学习笔记 记录得比较凌乱&#xff0c;不尽详细 day13 文件上传 代码自主写 编辑器引用 ueditor 文件下载 直连下载 传参下载 直连下载 中间件决定下载文件类型 直连一般没有问题 传参下载可能存在安全问题 文件删除 文件删除目录…

【C语言__结构体__复习篇5】

目录 前言 一、结构体基础知识 1.1 结构体的语法形式 1.2 创建结构体变量 1.3 结构体变量的初始化 1.4 点(.)操作符和箭头(->)操作符 二、匿名结构体 三、结构体自引用 四、结构体内存对齐 4.1 内存对齐的规则 4.2 出现结构体内存对齐的原因 4.3 修改默认对齐数 五、结…

代码随想录算法训练营第四十九天|leetcode516、647题

1、leetcode第647题 本题要求找字符串中回文子串的数目&#xff0c;因此设置dp数组&#xff0c;dp[i][j]的含义是从下标i到j的子串是不是回文串&#xff0c;因此递推公式为&#xff1a;在s[i]s[j]时如果间距小于等于1或者间距大于1时dp[i1][j-1]为回文串则dp[i][j]也为回文串。…

2024 EasyRecovery三分钟帮你恢复 电脑硬盘格式化

随着数字化时代的到来&#xff0c;我们的生活和工作中越来越依赖于电子设备。然而&#xff0c;电子设备中的数据丢失问题也随之而来。数据丢失可能是由各种原因引起的&#xff0c;如硬盘故障、病毒感染、误删除等。面对这种情况&#xff0c;一个高效、可靠的数据恢复工具变得尤…

Stable Diffusion教程:LoRA模型

LoRA模型是一种微调模型&#xff0c;它不能独立生成图片&#xff0c;常常用作大模型的补充&#xff0c;用来生成某种特定主体或者风格的图片。 下载模型 在模型下载网站&#xff0c;如果模型是LoRA模型&#xff0c;网站会特别标识出来。以 liblib.ai为例&#xff1a; 模型左…

TCP三次握手的原因

三次握手才可以阻止重复历史连接的初始化&#xff08;主要原因&#xff09;三次握手才可以同步双方的初始序列号三次握手才可以避免资源浪费为了确认双方的接收能力和发送能力都正常 为了实现可靠传输&#xff0c; 通信双方需要判断自己已经发送的数据包是否都被接收方收到&…

浏览器内使用JS和椭圆曲线密钥交换

源码&#xff1a; 之前使用GO已经可以实现秘钥交换了&#xff0c;这里使用浏览器发送数据&#xff0c;与后端服务实现秘钥交换&#xff0c;记录一下实现的基本函数&#xff1a; // 生成密钥对&#xff0c;并保存到全局变量中async function createDHPair() {// 生成新的ECD…

“手撕“三大特性之一的<继承>(上)

目录 一、为什么需要继承 二、什么是继承 三、继承怎么写 四、成员的访问 1.父类与子类的成员变量不同名 2.父类与子类的成员变量同名 3.父类与子类的成员方法不同名 4.父类与子类的成员方法同名 五、super关键字 一、为什么需要继承 先让我们看一段Java代码&#…

Android Studio历史版本下载地址

https://developer.android.com/studio/archive?hlzh-cn https://blog.csdn.net/crasowas/article/details/130304836

蛋白质致病突变的计算方法(二)

&#xff08;继续上一篇&#xff09; 2 致病和中性突变数据库 高通量和低成本的DNA测序技术有助于积累&#xff08;accumulate&#xff09;大规模突变数据&#xff0c;并且&#xff0c;各种生物数据库在文献中已经被报道。这些数据库存在一些优势特性&#xff0c;结构化存储、…

MySQL数据加密,模糊查询

实现配置文件加密&#xff0c;数据库敏感字段加密&#xff0c;加密字段模糊查询 配置文件加密使用Jasypt。数据库加密解密方法自己用java实现mysql的aes_encrypt和aes_decrypt方法&#xff0c;查询时先用mysql的解密方法aes_decrypt把加密字段解密再用like查。 配置文件加密参…

Leetcode 4. 寻找两个正序数组的中位数

心路历程&#xff1a; 这道题暴力解很简单&#xff0c;一看到要求O(log(mn))的复杂度就只能是双指针&#xff0c;但是实测发现这道题用归并排序更快。这可能就是平均复杂度和实际复杂度的Gap吧。 二分法的思路&#xff1a; 要找到第 k (k>1) 小的元素&#xff0c;那么就取…

React + Ts + Vite + Antd 项目搭建

1、创建项目 npm create vite 项目名称 选择 react 选择 typescript 关闭严格模式 建议关闭严格模式&#xff0c;因为不能自动检测副作用&#xff0c;有意双重调用。将严格模式注释即可。 2、配置sass npm install sass 更换所有后缀css为sass vite.config.ts中注册全局样式 /…

windows命令行安装工具/包/软件后,命令行命令找不到(npm示例)

问题描述 在命令行安装工具&#xff0c;比如npm install, 或者windows自带的包管理工具&#xff0c;如Chocolatey&#xff0c;Scoop&#xff0c;WinGet等&#xff0c;安装软件后&#xff0c;然后直接在命令行运行上面安装的指令会提示命令找不到。这让经常使用linux&#xff0…

scss 和css 的区别 scss变量和css变量的区别

scss 和 css 的区别 语法差异&#xff1a; CSS 使用大括号 {} 和分号 ; 来定义样式规则和属性。SCSS 使用了 Sass 的语法&#xff0c;它允许使用类似编程语言的结构&#xff0c;如变量、嵌套规则、混合&#xff08;mixins&#xff09;和继承等。 嵌套规则&#xff1a; 在 SCSS …