Summer self-study day 18 | spring (IV)

Time:2021-12-4

IOC annotation

After creating an object with annotations, you don’t have to manually configure the properties of the created object through the bean tag as before.
The annotation should be written in front of the class or member method to be injected.
They are divided into four categories according to their functions:

create object

  • Same function as bean tag
    • @Component – stores the current object in the spring container
    • Attribute: Value: Specifies the ID of the bean. The default value is the current class name, but the first letter should be lowercase
    • Derived annotation: make the three-tier object clearer, equivalent to the subclass of @ component
      • @Controller: presentation layer
      • @Service: business layer
      • @Repository: persistence layer

Configure the context namespace in bean.xml

<?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">

<!--  Label required to configure Component annotation -- >
    <context:component-scan base-package="spring.selflearning"></context:component-scan>

</beans>

Injection data

  • Same function as property
  • @Autowired: automatically inject data according to type, as long as there is in the containeronlyIf the type of a bean object matches the type of variable to be injected, the injection will succeed.
    • It can appear on variables or methods.
    • The set method is not required at this time
  • @Qualifier: inject by name on the basis of type injection. It cannot be used alone when injecting class members. It can be used when injecting method parameters.
  • @Value: inject basic type and string type
  • Collection type injection can only be implemented through XML
  • Change the scope of action
    • Same as scope
    • @Scope, which can be singleton or prototype
  • Life cycle related
    • It works the same as init method and destroy method
    • @Predestroy destroy
    • @Postconstruct initialization
    • You need to release the container with the close () method
    • Only singleton objects can be destroyed

Some new annotations of spring

These new annotation functions are the same as some properties in bean. XML to replace the configuration mode in bean. XML.

@Configuration

  • Indicates that the current class is a configuration class
  • When the configuration class is used as a parameter created by the annotationconfigapplicationcontext object, the annotation may not be written.

If used in a methodApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);If you create an object, you don’t need to use the @ configuration annotation on the method, because Java will find it automaticallySpringConfiguration.classThis configuration class creates objects.

AnnotationConfigApplicationContextMethod can write multiple configuration classes separated by commas.

@ComponentScan

  • Specify the packages that spring needs to scan when creating containers; Property: basepackages
  • Function and<context:component-scan base-package="spring.selflearning"></context:component-scan>Same.

@Bean

  • Store the return value of the current method as a bean object in the IOC container; Property: name, specifies the ID of the bean. When not written, the default value is the name of the current method
  • If the bean annotation has a value, spring will look for available bean objects in the container in the same way as the function of the Autowired annotation

To annotate the method of creating a queryrunner object:

    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

@Import

  • Specifies the bytecode of other configuration classes
  • The class after using the import annotation is the parent configuration class, and the imported is the child configuration class. At this time, when creating an object, you only need to annotate the parent class configuration class.

PropertySource

  • Used to specify the location of the properties
  • @Value: Specifies the file path and name, classpath, which indicates that it is under the classpath
  • In my actual use, I found that the value annotation cannot normally read the properties configuration file. At present, this problem has not been solved. Attach your own code:

Parent configuration class:SpringConfiguration.java

@Componentscan (basepackages = "spring. Selflearning") // the attribute is an array type. If you need to scan multiple classes, you need to enlarge the parentheses
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {}

Sub configuration class:JdbcConfig.java

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.sql.DataSource;

@Component("jdbcConfig")
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    public String getDriver() {
        return driver;
    }

    public String getUrl() {
        return url;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }
        catch(Exception e) {
            throw  new RuntimeException(e);
        }
    }
}

jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=1234

About when to use XML and when to use annotations

In fact, annotations do not always reduce the amount of code in the configuration process, such as when configuring a JDBC connection.
If the configuration injected object is in a class written by others, it is better to use XML; If you write your own class, it is more convenient to add annotations directly to the class.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Hive built-in function summary

1. Related help operation functions View built-in functions: Show functions; Display function details: desc function ABS; Display function extension information: desc function extended concat; 2. Learn the ultimate mental method of built-in function Step 1: carefully read all the functions of the show functions command to establish an overall understanding and impression Step 2: use […]