How to dynamically inject bean instances in spring
preface
There are many ways to inject instances in spring, but due to the different initialization order, the annotation based injection method is easy to fail to be injected correctly.
This article will introduce a dynamic method to extract spring managed beans in a real project. I won't say much now. Let's take a look at the detailed introduction.
1、 Annotation based injection of instances
When a bean needs to be initialized, its dependent objects must be initialized. If the injected object is initialized later than the current object, the injected object will be null
1.1 @Autowired
Load spring managed beans by type. By default, its bean must exist. If its bean is null, you can set its required property to false. For details, please refer to the source code:
If you need to inject beans based on commands, you need to use @ qualifier to label the name. The code example is as follows:
Scope of application: variables, setter methods and constructors.
Source: Spring Framework
1.2 @Inject
By javax inject. Inject provides automatic assembly based on type. If you need to transfer by name, you need to use @ named together. This usage is very similar to @ Autowired provided by the spring framework.
Scope of application: variable, setter method, constructor
Source: jsr330 specification javax extension package
Code example:
1.3 @Resource
By default, the injection is assembled by name. Only when no bean matching the name is found will the injection be assembled by type. It is available after JDK 1.6.
Scope of application: it can be applied to variables and setter methods
Source: provided after JDK 1.6
Code usage example:
2、 Dynamic injection mode
Idea: get the reference of ApplicationContext based on applicationcontextaware, and then get the object dynamically based on ApplicationContext.
The implementation code is as follows:
After that, you can dynamically obtain the required bean instances directly in the code:
Is it very easy to use?
summary
Here are various ways to inject beans into spring. Each has its own advantages and disadvantages. You can choose to use it.
Well, the above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.