电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Springboot自動裝配實現過程代碼實例

瀏覽:6日期:2023-05-12 16:40:35

創建一個簡單的項目:

<?xml version='1.0' encoding='UTF-8'?><project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.1.12.RELEASE</version> </parent> <groupId>com.xiazhi</groupId> <artifactId>demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies></project>

首先創建自定義注解:

package com.xiazhi.demo.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * MyComponent 作用于類上,表示這是一個組件,于component,service注解作用相同 * @author zhaoshuai */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface MyComponent {}

package com.xiazhi.demo.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * 作用于字段上,自動裝配的注解,與autowired注解作用相同 * @author zhaoshuai */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Reference {}

然后寫配置類:

package com.xiazhi.demo.config;import com.xiazhi.demo.annotation.MyComponent;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.context.ResourceLoaderAware;import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;import org.springframework.core.io.ResourceLoader;import org.springframework.core.type.AnnotationMetadata;import org.springframework.core.type.filter.AnnotationTypeFilter;/** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/public class ComponentAutoConfiguration implements ImportBeanDefinitionRegistrar, ResourceLoaderAware { private ResourceLoader resourceLoader; @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { String className = annotationMetadata.getClassName(); String basePackages = className.substring(0, className.lastIndexOf('.')); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry, false); scanner.addIncludeFilter(new AnnotationTypeFilter(MyComponent.class)); scanner.scan(basePackages); scanner.setResourceLoader(resourceLoader); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; }}

上面是配置掃描指定包下被MyComponent注解標注的類并注冊為spring的bean,bean注冊成功后,下面就是屬性的注入了

package com.xiazhi.demo.config;import com.xiazhi.demo.annotation.MyComponent;import com.xiazhi.demo.annotation.Reference;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;import org.springframework.boot.SpringBootConfiguration;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.context.annotation.Bean;import org.springframework.util.ReflectionUtils;import java.lang.reflect.Field;/** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/@SpringBootConfigurationpublic class Configuration implements ApplicationContextAware { private ApplicationContext applicationContext; @Bean public BeanPostProcessor beanPostProcessor() { return new BeanPostProcessor() { /** * @company lihfinance.com * @author create by ZhaoShuai in 2020/3/21 * 在bean注冊前會被調用 * @param [bean, beanName] * @return java.lang.Object **/ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {return bean; } /** * @company lihfinance.com * @author create by ZhaoShuai in 2020/3/21 * 在bean注冊后會被加載,本次在bean注冊成功后注入屬性值 * @param [bean, beanName] * @return java.lang.Object **/ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {Class<?> clazz = bean.getClass();if (!clazz.isAnnotationPresent(MyComponent.class)) { return bean;}Field[] fields = clazz.getDeclaredFields();for (Field field : fields) { if (!field.isAnnotationPresent(Reference.class)) { continue; } Class<?> type = field.getType(); Object obj = applicationContext.getBean(type); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, obj);}return bean; } }; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }}

下面開始使用注解來看看效果:

package com.xiazhi.demo.service;import com.xiazhi.demo.annotation.MyComponent;import javax.annotation.PostConstruct;/** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/@MyComponentpublic class MyService { @PostConstruct public void init() { System.out.println('hello world'); } public void test() { System.out.println('測試案例'); }}

package com.xiazhi.demo.service;import com.xiazhi.demo.annotation.MyComponent;import com.xiazhi.demo.annotation.Reference;/** * @author ZhaoShuai * @company lihfinance.com * @date Create in 2020/3/21 **/@MyComponentpublic class MyConsumer { @Reference private MyService myService; public void aaa() { myService.test(); }}

啟動類要引入配置文件:

Springboot自動裝配實現過程代碼實例

import注解引入配置文件。

編寫測試類測試:

@SpringBootTest(classes = ApplicationRun.class)@RunWith(SpringRunner.class)public class TestDemo { @Autowired public MyConsumer myConsumer; @Test public void fun1() { myConsumer.aaa(); }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 闭端端子|弹簧螺式接线头|防水接线头|插线式接线头|端子台|电源线扣+护线套|印刷电路板型端子台|金笔电子代理商-上海拓胜电气有限公司 | 真空干燥烘箱_鼓风干燥箱 _高低温恒温恒湿试验箱_光照二氧化碳恒温培养箱-上海航佩仪器 | 曙光腾达官网-天津脚手架租赁-木板架出租-移动门式脚手架租赁「免费搭设」 | 定坤静电科技静电消除器厂家-除静电设备 | 压缩空气检测_气体_水质找上海京工-服务专业、价格合理 | 防爆电机生产厂家,YBK3电动机,YBX3系列防爆电机,YBX4节防爆电机--河南省南洋防爆电机有限公司 | 紫外荧光硫分析仪-硫含量分析仪-红外光度测定仪-泰州美旭仪器 | 牛皮纸|牛卡纸|进口牛皮纸|食品级牛皮纸|牛皮纸厂家-伽立实业 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 | YT保温材料_YT无机保温砂浆_外墙保温材料_南阳银通节能建材高新技术开发有限公司 | 中空玻璃生产线,玻璃加工设备,全自动封胶线,铝条折弯机,双组份打胶机,丁基胶/卧式/立式全自动涂布机,玻璃设备-山东昌盛数控设备有限公司 | 地埋式垃圾站厂家【佳星环保】小区压缩垃圾中转站转运站 | 空冷器|空气冷却器|空水冷却器-无锡赛迪森机械有限公司[官网] | 热缩管切管机-超声波切带机-织带切带机-无纺布切布机-深圳市宸兴业科技有限公司 | 衬塑设备,衬四氟设备,衬氟设备-淄博鲲鹏防腐设备有限公司 | 合肥触摸一体机_触摸查询机厂家_合肥拼接屏-安徽迅博智能科技 | YAGEO国巨电容|贴片电阻|电容价格|三星代理商-深圳市巨优电子有限公司 | 北京森语科技有限公司-模型制作专家-展览展示-沙盘模型设计制作-多媒体模型软硬件开发-三维地理信息交互沙盘 | 东莞海恒试验仪器设备有限公司 | LZ-373测厚仪-华瑞VOC气体检测仪-个人有毒气体检测仪-厂家-深圳市深博瑞仪器仪表有限公司 | IWIS链条代理-ALPS耦合透镜-硅烷预处理剂-上海顶楚电子有限公司 lcd条形屏-液晶长条屏-户外广告屏-条形智能显示屏-深圳市条形智能电子有限公司 | 东莞动力锂电池保护板_BMS智能软件保护板_锂电池主动均衡保护板-东莞市倡芯电子科技有限公司 | 微学堂-电动能源汽车评测_电动车性能分享网 | 权威废金属|废塑料|废纸|废铜|废钢价格|再生资源回收行情报价中心-中废网 | 清水-铝合金-建筑模板厂家-木模板价格-铝模板生产「五棵松」品牌 | 大巴租车平台承接包车,通勤班车,巴士租赁业务 - 鸿鸣巴士 | 密集架|电动密集架|移动密集架|黑龙江档案密集架-大量现货厂家销售 | 青岛空压机,青岛空压机维修/保养,青岛空压机销售/出租公司,青岛空压机厂家电话 | 热缩管切管机-超声波切带机-织带切带机-无纺布切布机-深圳市宸兴业科技有限公司 | 旅游规划_旅游策划_乡村旅游规划_景区规划设计_旅游规划设计公司-北京绿道联合旅游规划设计有限公司 | 合肥办公室装修 - 合肥工装公司 - 天思装饰 | 集装箱展厅-住人集装箱住宿|建筑|房屋|集装箱售楼处-山东锐嘉科技工程有限公司 | 煤棒机_增碳剂颗粒机_活性炭颗粒机_木炭粉成型机-巩义市老城振华机械厂 | 铝板冲孔网,不锈钢冲孔网,圆孔冲孔网板,鳄鱼嘴-鱼眼防滑板,盾构走道板-江拓数控冲孔网厂-河北江拓丝网有限公司 | 超细粉碎机|超微气流磨|气流分级机|粉体改性设备|超微粉碎设备-山东埃尔派粉碎机厂家 | IP检测-检测您的IP质量 | 高清视频编码器,4K音视频编解码器,直播编码器,流媒体服务器,深圳海威视讯技术有限公司 | 不锈钢/气体/液体玻璃转子流量计(防腐,选型,规格)-常州天晟热工仪表有限公司【官网】 | 引领中高档酒店加盟_含舍·美素酒店品牌官网 | 冷却塔减速机器_冷却塔皮带箱维修厂家_凉水塔风机电机更换-广东康明冷却塔厂家 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 |