当前位置:网站首页>Inject Autowired fields into ordinary beans
Inject Autowired fields into ordinary beans
2022-04-23 19:26:00 【justry_ deng】
To the ordinary bean Conduct Autowired Field injection
Tool class
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/** * To the ordinary bean( namely : Not spring-bean) Of autowired Injection support * * @author JustryDeng * @since 2020/7/5 13:20:19 */
@Slf4j
public abstract class ExtAutowiredInjector {
public ExtAutowiredInjector() {
Object obj = applyAutowired();
ExtAutowiredInjector.inject(obj);
}
/** * For returned object Conduct autowired Injection treatment * * @return To be injected Object */
protected Object applyAutowired() {
return this;
}
/** * On the target object @Auwired Annotated fields are injected * * @param obj * The goal is obj */
public static void inject(Object obj) {
if (obj == null) {
log.warn("obj is null, skip inject.");
return;
}
if (ExtAutowiredInjectorProcessor.applicationContext != null) {
ExtAutowiredInjectorProcessor.applicationContext.publishEvent(new AutowiredInjectEvent(obj));
} else {
ExtAutowiredInjectorProcessor.queue.add(obj);
}
}
/** * Autowired Inject support events * * @author JustryDeng * @since 2020/7/5 15:02:19 */
public static class AutowiredInjectEvent extends ApplicationEvent {
@Getter
private final Object bean;
/** * Create a new ApplicationEvent. * * @param source * the object on which the event initially occurred (never {@code null}) */
public AutowiredInjectEvent(Object source) {
super(source);
Objects.requireNonNull(source, "source cannot be null.");
this.bean = source;
}
}
/** * {@link ExtAutowiredInjector} processor * * @author JustryDeng * @since 2020/7/5 13:46:25 */
@Slf4j
@Component
public static class ExtAutowiredInjectorProcessor implements SmartInitializingSingleton, ApplicationListener<AutowiredInjectEvent> {
static ApplicationContext applicationContext;
static Queue<Object> queue = new ConcurrentLinkedQueue<>();
private final AutowireCapableBeanFactory autowireCapableBeanFactory;
public ExtAutowiredInjectorProcessor(AutowireCapableBeanFactory autowireCapableBeanFactory,
ApplicationContext applicationContext) {
this.autowireCapableBeanFactory = autowireCapableBeanFactory;
ExtAutowiredInjectorProcessor.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(@NonNull AutowiredInjectEvent event) {
Object bean = event.getBean();
autowireCapableBeanFactory.autowireBean(bean);
afterSingletonsInstantiated();
}
@Override
public void afterSingletonsInstantiated() {
Object obj = queue.poll();
while (obj != null) {
autowireCapableBeanFactory.autowireBean(obj);
obj = queue.poll();
}
}
}
}
Use tests
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
/** * start class * * @author JustryDeng * @since 2022/4/21 11:41 */
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
// start-up springboot project , Observe the input
// Test one , Output :hello Deng eryang ~
new TestClassOne().who();
// Test two , Output :hello Deng Shuai ~
TestClassTwo testClassTwo = new TestClassTwo();
ExtAutowiredInjector.inject(testClassTwo);
testClassTwo.who();
// It doesn't matter to inject repeatedly
//ExtAutowiredInjector.inject(testClassTwo);
//ExtAutowiredInjector.inject(testClassTwo);
//ExtAutowiredInjector.inject(testClassTwo);
//testClassTwo.who();
}
/** * Test usage I : To use by inheritance , Automatically complete the injection */
public static class TestClassOne extends ExtAutowiredInjector {
@Autowired
@Qualifier("demoApplication.DengErYang")
private Mine mine;
public void who() {
System.err.println(mine.hello());
}
@Override
protected Object applyAutowired() {
return this;
}
}
/** * Test usage I : No inheritance , Direct use {@link ExtAutowiredInjector#inject(Object)} Inject */
public static class TestClassTwo {
@Autowired
@Qualifier("demoApplication.DengShuai")
private Mine mine;
public void who() {
System.err.println(mine.hello());
}
}
public interface Mine {
String hello();
}
@Component(value = "demoApplication.DengErYang")
public static class DengErYang implements Mine {
@Override
public String hello() {
return "hello Deng eryang ~";
}
}
@Component(value = "demoApplication.DengShuai")
public static class DengShuai implements Mine {
@Override
public String hello() {
return "hello Deng Shuai ~";
}
}
}
Start the program , Console output :
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.6)
2022-04-21 13:47:39.176 INFO 15784 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 1.8.0_291 on DESKTOP-K08MNSB with PID 15784 (E:\working\demo\demo\target\classes started by Dunsullivan in E:\java\flex-server)
2022-04-21 13:47:39.179 INFO 15784 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-21 13:47:39.480 INFO 15784 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.509 seconds (JVM running for 0.9)
hello Deng eryang ~
hello Deng Shuai ~
Process finished with exit code 0
Related information
- This article has been included in 《 Programmer growth notes 》 , The author JustryDeng
版权声明
本文为[justry_ deng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231923567388.html
边栏推荐
- Go three ways to copy files
- 山大网安靶场实验平台项目—个人记录(四)
- openlayers 5.0 加载arcgis server 切片服务
- C1000k TCP connection upper limit test
- Redis core technology and practice 1 - start with building a simple key value database simplekv
- Grafana 分享带可变参数的链接
- SSDB foundation 2
- Web Security
- MySQL syntax collation (2)
- Intuitive understanding of the essence of two-dimensional rotation
猜你喜欢

指针数组与数组指针的区分

Openharmony open source developer growth plan, looking for new open source forces that change the world!

Why is PostgreSQL about to surpass SQL Server?

NiO related Basics

OpenHarmony开源开发者成长计划,寻找改变世界的开源新生力!
![[报告] Microsoft :Application of deep learning methods in speech enhancement](/img/c1/7bffbcecababf8dabf86bd34ab1809.png)
[报告] Microsoft :Application of deep learning methods in speech enhancement

MySQL syntax collation

Kubernetes入门到精通-KtConnect(全称Kubernetes Toolkit Connect)是一款基于Kubernetes环境用于提高本地测试联调效率的小工具。

Grafana 分享带可变参数的链接

2021-2022-2 ACM集训队每周程序设计竞赛(8)题解
随机推荐
An idea of rendering pipeline based on FBO
A brief explanation of golang's keyword "competence"
坐标转换WGS-84 转 GCJ-02 和 GCJ-02转WGS-84
Wechat applet part of the mobile phone Preview PDF did not respond
Grafana 分享带可变参数的链接
Oracle configuration st_ geometry
C语言的十六进制printf为何输出有时候输出带0xFF有时没有
Machine learning catalog
LPC1768 关于延时Delay时间与不同等级的优化对比
JVM的类加载过程
MySQL lock
js 计算时间差
Parsing headless jsonarray arrays
Translation of audio signal processing and coding: Preface
[transfer] summary of new features of js-es6 (one picture)
Main differences between go and PHP
Openlayers 5.0 loading ArcGIS Server slice service
Reflection on the performance of some OpenGL operations in the past
openlayers 5.0 当地图容器大小改变时,重新加载地图
SSDB foundation 2