Springboot自动装配实现过程代码实例
作者:Zs夏至 发布时间:2023-11-14 19:50:19
标签:Spring,boot,自动,装配
创建一个简单的项目:
<?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
**/
@SpringBootConfiguration
public 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
**/
@MyComponent
public 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
**/
@MyComponent
public class MyConsumer {
@Reference
private MyService myService;
public void aaa() {
myService.test();
}
}
启动类要引入配置文件:
import注解引入配置文件。
编写测试类测试:
@SpringBootTest(classes = ApplicationRun.class)
@RunWith(SpringRunner.class)
public class TestDemo {
@Autowired
public MyConsumer myConsumer;
@Test
public void fun1() {
myConsumer.aaa();
}
}
来源:https://www.cnblogs.com/Zs-book1/p/12540571.html
0
投稿
猜你喜欢
- 本文实例为大家分享了iOS新浪微博分享功能的具体代码,供大家参考,具体内容如下做新浪分享 需先去http://open.weibo.com/
- 1、取得控制台应用程序的根目录方法方法1、Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径方法
- 1、properties文件显示乱码问题原因是因为properties默认使用ASCII码,就算在文件中填写了中文,再打开后依然会转换成AS
- java通过IP解析地理位置在项目开发中,需要在登录日志或者操作日志中记录客户端ip所在的地理位置。目前根据ip定位地理位置的第三方api有
- 最近项目中使用springboot+jwt实现登录权限控制,所以在这里记录一下防止以后忘记,毕竟好记性不如烂笔头嘛~。首先我们需要导入使用到
- 基础环境SpringBoot、Maven代码实现1.添加依赖<!--二维码生成 --><dependency&
- 建议缓存放到 service 层,你可以自定义自己的 BaseServiceImpl 重写注解父类方法,继承自己的实现。为了方便,这里我们将
- 本文实例为大家分享了Java实现抢红包功能的具体代码,供大家参考,具体内容如下关键思想:1.抢红包涉及多人并发操作,需要做好同步保证多线程运
- Springboot对配置文件的敏感信息加密前言最近公司对软件的安全问题比较在意,要求对配置文件中的敏感信息如数据库密码等进行加密。但是Sp
- 对象创建的几种方法:使用new关键字使用clone方法反射机制反序列化以上四种都可以产生java对象1,3都会明确的显式的调用构造函数2是在
- 什么是POM?POM是项目对象模型(Project Object Model)的简称,它是Maven项目中的文件,使用XML表示,名称叫做p
- 项目地址:gitee.com/baojh123/rp…netty-study 这个项目是没用到的,可以删掉,主要是测试
- SSM在Controller中添加事务管理本人使用:集成开发环境:idea项目管理工具:maven数据库:oracle框架:Spring+S
- SpringBoot项目中新增脱敏功能项目背景目前正在开发一个SpringBoot项目,此项目有Web端和微信小程序端。web端提供给工作人
- 一个中大型的 Java 项目往往包含若干 JAR 包,这些 JAR 包有着不同的版本号。如果这些 JAR 包单独发布,然后直接通过版本号引用
- 前言LocalDateTime、LocalDate、LocalTime 是 Java8 全新的日期框架,加强了对时间的管理,有很多特别好用的
- 相信不少喜欢开发的朋友都已经知道微信小程序是个什么物种了,楼主也是从小程序内测期间就开始关注,并且也写过几个已经上线的微信小程序。但是基本上
- 以前公司的产品已经上线20多年了,主要是维护,也就是改bug。每周我们Team会从Jira上拿我们可以改的bug,因为每个团队负责的业务范围
- 本文实例讲述了java获取百度网盘真实下载链接的方法。分享给大家供大家参考。具体如下:目前还存在一个问题,同一ip在获取3次以后会出现验证码
- 技术场景在日常的开发、测试或运维的过程中,经常存在这样的场景,开发人员在代码中使用日志工具(log4j、slf4j)记录日志,比如请求ID、