Inject beans through annotations

background

When we talk about Spring, we must mention the IOC container and DI dependency injection. Spring achieves the effect of inversion of control by injecting methods labeled Bean by Bean into the IOC container. So when we first get to know beans, we must inject them one by one using XML files, such as the following.

	<bean id="bean" class="beandemo.Bean" />
Copy the code

Our projects are typically large and require hundreds or thousands of beans to use, which can be tedious to write. Spring then helps us implement a way to implement injection through annotations. Just add annotations in front of the classes you need to inject, and Spring will help us scan them for injection.

XML scan package method

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

The general form of injection through annotations

In general, injection beans have one of the most straightforward and easy-to-understand ways to implement injection.


  • The Bean class
	public class MyBean{}Copy the code
  • The Configuration class
	// Create a class profile
	@Configuration
	public class MyConfiguration{
		// Commit a Bean to Spring for management
        @Bean
        public MyBean myBean(a){
            return newMyBean(); }}Copy the code
  • The Test class

With XML is a bit different, here in the Test, is no longer a ClassPathXmlApplicationContext instantiation, but get AnnotationConfigApplicationContext instance.

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

In the above code, MyBean is just a Bean that we need Spring to manage. It’s just a simple class. In MyConfiguration, we first mark the class with the @Configuration annotation, which indicates that the class is a Spring Configuration class and will be loaded when the Configuration is loaded.

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

Inject beans through constructors

When we generate a Bean instance, we can inject the Bean implementation using the Bean constructor. Look directly at the code


  • The Bean class
	@Component
	public class MyBeanConstructor {

    	private AnotherBean anotherBeanConstructor;

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

    	@Override
    	public String toString(a) {
        	return "MyBean{" +
            	"anotherBeanConstructor=" + anotherBeanConstructor +
            	'} '; }}Copy the code
  • AnotherBean class
	@Component(value="Bean ID, default class name small hump")
	public class AnotherBean {}Copy the code
  • The Configuration class
	@Configuration
	@ComponentScan("com.company.annotationbean")
	public class MyConfiguration{}Copy the code

Here we can see that the new annotations are different from the normal way of injecting code. Let’s see what they mean:

  • @AutoWired

If you want to know why auto assembly wrench. Read the explanation of the next note. If you specify a Bean ID when injecting here, use the @qualifier annotation

  • @Component (default singleton mode)

What?? This translates to parts, why does it feel like repairing a car? Yes, Spring’s approach to managing beans is a way of fixing cars. We added the @conmonent annotation when we needed to turn a class into a Bean that Spring could inject, so we could mount the Bean like a part :wrench: on the IOC car

Here we have a few other annotations that do the same thing: the @component refinement:

    • The @Controller notation is in the Controller layer
    • The @service annotation is in the Service layer
    • The @repository annotation is in the DAO layer
  • @ComponentScan(“”)

Spring will scan the package and inject all the classes labeled @Component in it.

We were assembling the MyBean part and realized that it had to be built on top of the AnotherBean to build into IOC, so we auto-assembly: Wrench: AnotherBean every time we assembled the MyBean. For example :chestnut:

Or take the car as an example, before we step on the gas to start, do we have to start? AutoWired is like starting a car, if you don’t start the car, it doesn’t matter if you step off the accelerator, it won’t even go.

Inject beans through the set method

We can inject the Bean implementation in the set method of an attribute. Look at the code


  • MyBean class
	@Component
	public class MyBeanSet {

    	private AnotherBean anotherBeanSet;

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

    	@Override
    	public String toString(a) {
        	return "MyBeanSet{" +
            	"anotherBeanSet=" + anotherBeanSet +
            	'} '; }}Copy the code
  • Configuration class and Test class

Same as the previous one, will not stick


Here we see that on the setter method we have an @autowired. Unlike the above, we don’t auto-assemble the :wrench: object when we instantiate the class, but when we explicitly call the setter.

Inject beans through properties

Our previous two injection methods such as different time, and more code, if through attributes, that is

	@Component
	public class MyBeanProperty {

    	@Autowired
    	private AnotherBean anotherBeanProperty;

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

Here we can see that we need to use AnotherBean as an instance object in our class, which we can automatically assemble with @AutoWired.

For those who ask about private attributes, how does Spring load them into IOC? I recommend looking at reflection

Inject beans through a List

  • MyBeanList class
	@Component
	public class MyBeanList {

    	private List<String> stringList;

    	@Autowired
    	public void setStringList(List<String> stringList) {
        	this.stringList = stringList;
    	}

    	public List<String> getStringList(a) {
        	returnstringList; }}Copy the code
  • MyConfiguration class
	@Configuration
	@ComponentScan("annoBean.annotationbean")
	public class MyConfiguration {

	    @Bean
	    public List<String> stringList(a){
	       List<String> stringList = new ArrayList<String>();
 	       stringList.add("List-1");
 	       stringList.add("List-2");
 	       returnstringList; }}Copy the code

Here we’re injecting MyBeanList, one element at a time. Here’s another way to inject a List

  • MyConfiguration class
	@Bean
    // Use this annotation to set the priority of Bean injection, not necessarily sequential numbers
    @Order(34)
    public String string1(a){
        return "String-1";
    }

    @Bean
    @Order(14)
    public String string2(a){
        return "String-2";
    }
Copy the code

Injecting the same type as the generic type in the List will automatically match the type, even though there is no sense of a List, just the type of String, but it will be injected through the Bean of the List.

The second method takes precedence over the first method, and when both exist, to force the first method, specify the id of the Bean

Inject beans through a Map

	@Component
	public class MyBeanMap {

    	private Map<String,Integer> integerMap;

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

    	@Autowired
    	public void setIntegerMap(Map<String, Integer> integerMap) {
    	    this.integerMap = integerMap; }}Copy the code
	@Bean
    public Map<String,Integer> integerMap(a){
        Map<String,Integer> integerMap = new HashMap<String, Integer>();
        integerMap.put("map-1".1);
        integerMap.put("map-2".2);
        return integerMap;
    }

    @Bean
    public Integer integer1(a){
        return 1;
    }

    @Bean
    public Integer integer2(a){
        return 2;
    }
Copy the code

There are also two ways to inject map-type beans, and the second has a higher priority than the first

These are just a few of the ways in which beans can be injected through annotations, in contrast to XML injection.