Spring family related notes

Posted by angelena on Sun, 26 Dec 2021 19:04:57 +0100

1, @ Component, @ repository, @ Service, @ Controller

(1) @ Component put the ordinary java class creation object into the Spring container

Equivalent to < bean id = "" class = "" > in xml configuration file</ bean>
For example:

public class Cat {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myCat" class="com.gushi.web.Cat">
        <property name="name" value="Tom Cat"/>
        <property name="age" value="3"/>
    </bean>

</beans>

If you use the @ Component annotation on the class, you don't have to write an xml configuration file.

@Component("myCat")
public class Cat {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

(2) @ repository is similar to @ Component, with different classification. It acts on persistence layer objects, indicating that objects can access the database.

(3) @ Service is similar to @ Component, with different classification. It acts on business layer objects, handles business logic, and has transaction capability.

(4) @ Controller is similar to @ Component and has different classifications. It acts on Controller objects (view layer objects), receives requests and displays the processing results of requests.

2, @ Value injects the Value in the configuration file into the variable

configuration file

school.name=dawn
school.age=13

Java class

public class Student {

    @Value("school.name") // Add the configuration file to school The value of name is assigned to name
    private String name;

    @Value("school.age") // Add the configuration file to school The value of age is assigned to age
    private Integer age;
}

3, @ Configuration @Bean

Spring uses xml as the container configuration file, and java classes can be used as the configuration file after 3.0.
Using Java classes as Configuration files requires two annotations: @ Configuration and @ Bean
@Configuration: placed on the top of the class, indicating that the class is used as a configuration file and can replace the xml configuration file
@Bean: put it on the method, declare the object, and inject the object into the container, which is mainly used in the class annotated with @ Configuration. If you do not specify an object name, in the container, the default id is the method name.

Create data class Student

package com.gushi.myannotation.domain;

public class Student {

    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Using xml as the container configuration file, create the Spring xml configuration file in the resources directory

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

<!--statement bean object-->
<bean id="myStudent" class="com.gushi.myannotation.domain.Student">
< property name="id" value="1001" />
< property name="name" value="dawn" />
< property name="age" value="15" />
</bean>

</beans>

Use class as container configuration file

@Configuration
public class MyConfig {

    @Bean("myStudent")
    public Student creatStudent(){

        Student student = new Student();
        student.setId(1001);
        student.setName("dawn");
        student.setAge(15);

        return student;

    }
}

Using unit tests

@Test
    public void xmlTest(){
        String config = "applicationContext.xml"; // The Spring configuration file created in the resources directory
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        Student student = (Student)ctx.getBean("myStudent");
        System.out.println("xml Created as a profile bean object" + student);
    }

    @Test
    public void configTest(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
        Student student = (Student)ctx.getBean("myStudent");
        System.out.println("Created using class as configuration file bean object" + student);
    }

4, @ ImportResource

@ImportResource: imports the xml configuration, which is equivalent to the resources of the xml file

<import resources="Other profiles"/>

Create data class Dog

public class Dog {

    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Using xml configuration files

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

    <bean id="myDog" class="com.gushi.myannotation.domain.Dog">
        <property name="id" value="1001" />
        <property name="name" value="Wangcai"/>
        <property name="age" value="3" />
    </bean>

</beans>

Create configuration class

@Configuration
// Use classpath to specify the classpath. It is compiled and under the classes under target
@ImportResource(value = "classpath:applicationContext.xml")
public class MyConfig {

    }
}

Use @ ImportResource to import the bean s in xml into the container. The classpath in the parameter refers to the classpath after compilation, and the IDEA is under the classes under the target.
@The source code of the parameter value of ImportResource(value = "") is as follows:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.core.annotation.AliasFor;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ImportResource {
    @AliasFor("locations")
    String[] value() default {};

    @AliasFor("value")
    String[] locations() default {};

    Class<? extends BeanDefinitionReader> reader() default BeanDefinitionReader.class;
}

You can see that it is a String array. If there are multiple files, it can be written as follows:

@ImportResource(value = {"classpath:a.xml","classpath:b.xml","classpath:c.xml..."})

5, @ PropertyResource

@PropertyResource: read the properties property configuration file. Using the property configuration file, you can provide data outside the program code to realize external configuration. To modify relevant data, you can only change the configuration file without modifying the source code.

Create data class Cat

public class Cat {

    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Create a properties file in the resources directory of the IDEA, and provide data in the format of k=v in the properties file.

cat.id=1001
cat.name=Tom
cat.age=3

Use related annotations in data classes

@Component("cat")
public class Cat {

    @Value("${cat.id}")
    private Integer id;
    @Value("${cat.name}")
    private String name;
    @Value("${cat.age}")
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Add relevant annotations to the configuration class

@Configuration
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.gushi.myannotation.domain")
public class MyConfig {


    }
}

Topics: Java Spring Spring Boot Back-end