Spring 5 from entry to grave: developing with annotations

Posted by johanafm on Wed, 02 Feb 2022 06:10:49 +0100

jdk1.5 start supporting annotations, spring 2 5 start comprehensive direct annotation

Preparation: inject attributes by annotation

1. Introduce the context file header into the spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

2. Enable annotation support

    <context:annotation-config/>

@Autowired

·@Autowired is automatically assembled by type and does not support id matching

·Packages that need to be imported into spring AOP

Test:

1. Remove the set method from the people class and use the @ Autowired annotation

package pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
    @Autowired
    private  Cat cat;
    @Autowired
    private  Dog dog;
    private  String name;
//After using annotations, you can omit the set method
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

2. The content of the configuration file at this time

     <bean id="dog" class="pojo.Dog"/>
    <bean id="cat" class="pojo.Cat"/>
      <bean  id="people" class="pojo.People" >
     </bean>

3. Testing

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.People;

public class Test01 {
    @Test
    public void  test01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        People people=context.getBean("people",People.class);
        people.getDog().shout();
        people.getCat().shout();
    }
}

 @Qualifier

·@Autowired automatically assembles according to the type, and @ Qualifier can automatically assemble according to byName

·@ Qualifier cannot be used alone.

Test steps:

1. Modify the content of the configuration file to ensure that there are objects of type. And the name is not the default name of the class

   <bean id="dog1" class="pojo.Dog"/>
    <bean id="cat1" class="pojo.Cat"/>
    <bean id="dog2" class="pojo.Dog"/>
    <bean id="cat2" class="pojo.Cat"/>

2. No Qualifier test is added and an error is reported directly

3. Add a Qualifier annotation to the attribute

public class People {
    @Autowired
    @Qualifier(value = "cat2")
    private  Cat cat;
    @Autowired
    @Qualifier(value = "dog2")
    private  Dog dog;
    private  String name;

4. Testing

 @Resource

·@If the Resource has a specified name attribute, first search the assembly by name according to the attribute

·Secondly, assemble in the default byName mode

·If none of the above is successful, it will be assembled automatically by byType

·If they are not successful, an exception is reported

Entity class:

  //If the allowed object is null, set required=false, and the default is true
  @Resource(name = "cat2")
    private  Cat cat;
    @Resource
    private  Dog dog;
    private  String name;

beans.xml

    <bean id="dog1" class="pojo.Dog"/>
    <bean id="cat1" class="pojo.Cat"/>
    <bean id="dog2" class="pojo.Dog"/>
    <bean id="cat2" class="pojo.Cat"/>
      <bean  id="people" class="pojo.People" >

Test successful!

Configuration file: beans XML} delete cat2

people.java} keep only annotations

Test: ok

Conclusion: the advanced byName search failed. Search byType again, success!

Summary

@Autowired and @ Resource

1. Both can be used to assemble bean s. Can be written on a field or on a setter method

2. @ Autowired is assembled by type by default (belonging to the spring specification). By default, dependent objects must exist. If null value is allowed, its required attribute can be set to false, such as @ Autowired(required=false). If we want to use name assembly, we can use it in combination with @ Qualifier annotation

3. @ Resource (belonging to J2EE complex return), assembled by name by default, and the name can be specified through the name attribute. If the name attribute is not specified, when the annotation is written on the field, the default is to take the field name to search by name. If the annotation is written on the setter method, the default is to take the attribute name for assembly. Only when no bean matching the name is found can it be assembled according to the type, but it should be noted that once the name attribute is specified, it will be assembled according to the name

They have the same function: they all inject objects by annotation, but the execution order is different@ Autowired bybye first, @ Resource byname first

Using annotation development

In the configuration file, a context constraint is introduced

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

Implementation of Bean

I used to use bean tags for bean injection, but in actual development, we usually use annotations

1. Notes under configuration scanning package

 <!--Specify annotation scan package-->
    <context:component-scan base-package="pojo"/>

2. Write a class under the specified class and add comments

Equivalent to < bean id = "user" class = "class under the current annotation" in the configuration file

import org.springframework.stereotype.Component;
@Component("user")
public class User {
   
    public  String name="Huaze lettuce";
}

3. Testing

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.User;
public class Mytest1 {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)context.getBean("user");
        System.out.println(user.name);
    }

}

Attribute injection

Using annotation injection attributes

1. You can add @ value ("value") to the direct name without providing a set method

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("user")
public class User {
@Value("Huaze lettuce")
    public  String name=;
}

2. If a set method is provided, add @ Value ("Value") to the set method;

Derived annotation

@Three derived annotations of Component

For better layering, Spring can use the other three annotations with the same functions. At present, which function is used is the same

·@Controller:web layer

·@Service: service layer

·@Repository: dao layer

Writing these annotations is equivalent to giving this class to the Spring management assembly

Auto assembly annotation

@scope

·Singleton: by default, Spring creates this object in singleton mode. Close the factory and all objects will be destroyed

·prototype: multi instance mode. Close the factory and all objects will not be checked. The internal garbage collection mechanism will recycle

Summary

XML and annotation comparison

·XML can be used in any scenario, with clear structure and convenient maintenance

·Annotations are not self provided classes and cannot be used. Development is simple and convenient

xml and annotation integrated development: Recommended Best Practices

`xml management Bean

·Annotation complete attribute injection

·In the process of using, you can not scan. The scanning is for the annotation on the class

effect:

·Make annotation driven registration to make annotations effective

·It is used to activate the annotations on the beans that have been registered in the spring container, that is, to register with spring

·If you do not scan the package, you need to configure the bean manually

·If the parent is driven without annotation, the injected value is null

Topics: Java Spring SSM intellij-idea