当前位置:网站首页>对普通bean进行Autowired字段注入
对普通bean进行Autowired字段注入
2022-04-23 19:24:00 【justry_deng】
对普通bean进行Autowired字段注入
工具类
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;
/** * 对普通bean(即:非spring-bean)的autowired注入支持 * * @author JustryDeng * @since 2020/7/5 13:20:19 */
@Slf4j
public abstract class ExtAutowiredInjector {
public ExtAutowiredInjector() {
Object obj = applyAutowired();
ExtAutowiredInjector.inject(obj);
}
/** * 对返回的object进行autowired注入处理 * * @return 要进行注入处理的Object */
protected Object applyAutowired() {
return this;
}
/** * 对目标对象中的被@Auwired标注了的字段进行注入 * * @param obj * 目标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注入支持事件 * * @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}处理器 * * @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();
}
}
}
}
使用测试
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 {
// 启动springboot项目, 观察输入
// 测试一,输出:hello 邓二洋~
new TestClassOne().who();
// 测试二,输出:hello 邓帅~
TestClassTwo testClassTwo = new TestClassTwo();
ExtAutowiredInjector.inject(testClassTwo);
testClassTwo.who();
// 重复注入也没关系
//ExtAutowiredInjector.inject(testClassTwo);
//ExtAutowiredInjector.inject(testClassTwo);
//ExtAutowiredInjector.inject(testClassTwo);
//testClassTwo.who();
}
/** * 测试用法一:继承使用,自动完成注入 */
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;
}
}
/** * 测试用法一:不继承, 直接用{@link ExtAutowiredInjector#inject(Object)}注入 */
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 邓二洋~";
}
}
@Component(value = "demoApplication.DengShuai")
public static class DengShuai implements Mine {
@Override
public String hello() {
return "hello 邓帅~";
}
}
}
启动程序,控制台输出:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: 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 邓沙利文 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 邓二洋~
hello 邓帅~
Process finished with exit code 0
相关资料
- 本文已被收录进《程序员成长笔记》 ,笔者JustryDeng
版权声明
本文为[justry_deng]所创,转载请带上原文链接,感谢
https://blog.csdn.net/justry_deng/article/details/124319942
边栏推荐
- Encyclopedia of professional terms and abbreviations in communication engineering
- Coordinate conversion WGS-84 to gcj-02 and gcj-02 to WGS-84
- How to select the third-party package of golang
- Go recursively loops through folders
- Common SQL commands
- MySQL syntax collation (3)
- 浅谈c语言指针的强制转换
- 点云数据集常用处理
- Some ideas about time-consuming needs assessment
- Codeworks round 783 (Div. 2) d problem solution
猜你喜欢
The platinum library cannot search the debug process records of some projection devices
ArcMap连接 arcgis server
binlog2sql 工具安装使用及问题汇总
Intuitive understanding of the essence of two-dimensional rotation
Oracle configuration st_ geometry
Keysight has chosen what equipment to buy for you
Partage de la conception de l'alimentation électrique de commutation et illustration des compétences en conception de l'alimentation électrique
MySQL syntax collation
RuntimeError: Providing a bool or integral fill value without setting the optional `dtype` or `out`
On the forced conversion of C language pointer
随机推荐
Zero base to build profit taking away CPS platform official account
ArcGIS JS API dojoconfig configuration
Pdf reference learning notes
Data analysis learning directory
White screen processing method of fulter startup page
MySQL practical skills
Speculation on the way to realize the smooth drag preview of video editing software
Openharmony open source developer growth plan, looking for new open source forces that change the world!
Golang timer
Solve the problem of invalid listview Click
Gossip: on greed
RuntimeError: Providing a bool or integral fill value without setting the optional `dtype` or `out`
All table queries and comment description queries of SQL Server
Redis core technology and practice 1 - start with building a simple key value database simplekv
Redis optimization series (III) solve common problems after master-slave configuration
Strange passion
Customize the non slidable viewpage and how to use it
Web Security
ArcMap publishing slicing service
Prefer composition to inheritance