Summary of some ways of injecting Spring into Bean

  • 2021-07-16 02:29:38
  • OfStack

Inject Bean with annotations

Background

When we talk about Spring, we will definitely mention IOC container, DI dependency injection, and Spring injects each class as Bean into IOC container, achieving the effect of inversion of control. So when we first came into contact with Bean, we must use xml files, and inject them one by one, such as the following.


	<bean id="bean" class="beandemo.Bean" />

If our project 1 is very large, we need hundreds of Bean to use, which is very cumbersome to write. Then Spring helps us realize a method of injection through annotation. Just pre-annotate the classes you need to inject, and Spring will help us scan them for injection.

The way xml scans packets


	<context:component-scan base-package="com.company.beandemo"/>

1 form injected by annotation

Under normal circumstances, Bean injection has one of the most straightforward and easy-to-understand ways to achieve injection. The following nonsense will not be said first, and the code will be posted first.

Class Bean


	public class MyBean{
	}

Configuration class


	// Create 1 A class Configuration file 
	@Configuration
	public class MyConfiguration{
		// Will 1 A Bean Hand over to Spring Manage 
 @Bean
 public MyBean myBean(){
  return new MyBean();
 }
	}

Class Test

Unlike xml, here in Test, instead of instantiating ClassPathXmlApplicationContext, you get an instance of AnnotationConfigApplicationContext.


	ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
	MyBean myBean = cotext.getBean("myBean",MyBean.class);
	System.out.println("myBean = " + myBean);

In the above code, MyBean is an Bean that we need Spring to manage. It is just a simple class. In MyConfiguration, we first marked the class with @ Configuration annotation, which indicates that the class is a configuration class of Spring, and it will be loaded when loading the configuration.

In MyConfiguration, we can see that a method returns an instance of MyBean, and the method is annotated with @ Bean, indicating that this is a method injecting Bean, which will inject the following returned Bean into IOC.

Injecting Bean through construction method

When we generate an instance of Bean, we can use the construction method of Bean to inject Bean implementation. Look directly at the code

Class Bean


	@Component
	public class MyBeanConstructor {

 	private AnotherBean anotherBeanConstructor;

 	@Autowired
 	public MyBeanConstructor(AnotherBean anotherBeanConstructor){
 	 this.anotherBeanConstructor = anotherBeanConstructor;
 	}

 	@Override
 	public String toString() {
 	return "MyBean{" +
  	"anotherBeanConstructor=" + anotherBeanConstructor +
  	'}';
 	}
	}

AnotherBean class


	@Component(value="Bean Adj. id The default is the class name Little Hump ")
	public class AnotherBean {
	}

Class Configuration


	@Configuration
	@ComponentScan("com.company.annotationbean")
	public class MyConfiguration{
	}

Here, we can find that it is different from the code injected in the same way. Let's take a look at what the new annotations mean:

@AutoWired

Simple and rude, which means automatic assembly: wrench:, I still don't understand why it is called automatic assembly: wrench:? Look at the explanation of the next annotation and you will know. If you specify an id of an Bean during injection here, use the @ Qualifier annotation

@ Component (default singleton mode)

What? ? This translates as a part. Why does it feel like repairing a car? ? Yes, the way Spring manages Bean is the way it repairs cars. We need to add annotation part @ Conmonent when we need to turn a class into an Bean that can be injected by Spring, so we can load Bean and assemble it like part 1: wrench: onto this IOC car
Here we have several other annotations that can also achieve this function, that is, the refined @ Component:

@ Controller annotated on Controller layer @ Service annotated on Service layer @ Repository annotated on dao layer @ComponentScan("")

Or translation and part scanning. Let's look at which "parts" (classes) need to be loaded in the "parts warehouse" in brackets. Spring will scan this package and inject all the classes marked @ Component.

It is easy to understand the injection by construction method here. When we assemble MyBean, we suddenly find that it must be installed in IOC on the basis of AnotherBean, so we will automatically assemble wrench: 1 AnotherBean every time we assemble MyBean. For example: chestnut:

Or take the car as an example. Do we have to start before stepping on the accelerator? ? The content of AutoWired here is like starting. If you don't start, it's useless for you to step on the accelerator. He won't leave.

Bean is injected by set method

We can inject the Bean implementation in the set method of 1 attribute, see the code

Class MyBean


	@Component
	public class MyBeanSet {

 	private AnotherBean anotherBeanSet;

 	@Autowired
 	public void setAnotherBeanSet(AnotherBean anotherBeanSet) {
  	this.anotherBeanSet = anotherBeanSet;
 	}

 	@Override
 	public String toString() {
  	return "MyBeanSet{" +
   	"anotherBeanSet=" + anotherBeanSet +
   	'}';
 	}
	}

Class Configuration and Class Test

If you are the same as the above one, you will not post it

Here we find that we have a @ AutoWired on the setter method. Unlike the above, we do not automatically assemble this object when we instantiate the class: wrench: This object, but when we explicitly call setter.

Injecting Bean through attributes

The first two injection methods are different in time and have more code. If it is through attributes, it is


	@Component
	public class MyBeanProperty {

 	@Autowired
 	private AnotherBean anotherBeanProperty;

 	@Override
 	public String toString() {
  	return "MyBeanProperty{" +
   	"anotherBeanProperty=" + anotherBeanProperty +
   	'}';
 	}
	}

Here we can see that we need to use the instance object AnotherBean in our class, and we can assemble it automatically through @ AutoWired.

For some small partners asking about private attributes, how does Spring load it into IOC? Recommended to look at reflexes

Injecting Bean through List

Class MyBeanList


	<context:component-scan base-package="com.company.beandemo"/>
0

Class MyConfiguration


	<context:component-scan base-package="com.company.beandemo"/>
1

Here we have injected MyBeanList, and the elements in List will be injected one by one. Another way to inject List is described below

Class MyConfiguration


	<context:component-scan base-package="com.company.beandemo"/>
2

Injecting a type like generic type 1 in List will automatically match the type. In time, there is no feeling of List, only the type of String, but it will be injected through Bean of List.

The priority of the second mode is higher than that of the first mode. When both modes exist, if you want to force the first mode to be used, you need to specify id of Bean

Injecting Bean through Map


	@Component
	public class MyBeanMap {

 	private Map<String,Integer> integerMap;

 	public Map<String, Integer> getIntegerMap() {
 	 return integerMap;
 	}

 	@Autowired
 	public void setIntegerMap(Map<String, Integer> integerMap) {
 	 this.integerMap = integerMap;
 	}
	}

	<context:component-scan base-package="com.company.beandemo"/>
4

Similarly, there are two ways to inject Map type Bean, and the priority value of the second is higher than that of the first

These are several ways of Bean injection through annotations, which can be compared with the way of xml injection.

Summarize


Related articles: