Spring learning notes

Time:2022-5-4

catalogue

1、 Spring files and notes

1. All spring configuration files

在这里插入图片描述

pom.xml

org.springframework
            spring-core
            5.3.7
        
        
            org.springframework
            spring-beans
            5.3.7
        
        
            org.springframework
            spring-context
            5.3.7
        
        
            org.springframework
            spring-context-support
            5.3.7
        
        
            org.springframework
            spring-web
            5.3.7
        
        
        
            org.springframework
            spring-test
            5.3.7
        
        
        
            org.springframework
            spring-webmvc
            5.3.7
        
        
        
            org.springframework
            spring-tx
            5.3.7
        
        
            org.springframework
            spring-jdbc
            5.3.7
        
        
        
            org.springframework
            spring-aop
            5.3.7
        
        
            org.springframework
            spring-aspects
            5.3.7

applicationContext.xml

Main.java

public static void main(String[] args) {
        /*Parse application Get bean instance (object) from XML configuration file*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*Object gets and casts the type*/
        UserDao userDao = (UserDao) app.getBean("userDao");
        /*Object call method*/
        userDao.save();
    }
/*Get file stream*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*Interface * // * interface implementation*/

        /*Get object * // * strong conversion object*/
        UserService userService = (UserService) app.getBean("userService");

        userService.save();

UserDao.java

public interface UserDao {
    /*Interface method*/
    public void save();
}

UserDaoImpl.java

public class UserDaoImpl implements UserDao {
    /*Method of class implementing interface*/
    public void save() {
        System. out. Println ("program start");
    }
}

2. All annotations of spring configuration

3. Key fundamentals of spring

1.Noun interpretation

  1. Class (human): entities with common featuresaggregate, template, one kind of thing, abstraction, concept, same kind of attribute


  2. Example: a real object


  3. Object (individual): the elements that make up the class, the concrete implementation of the class, and the actual executor


  4. Attribute: data (variable / value)


  5. Definition: compiler creates objects, allocates memory, and names (variable name / object name)


  6. Declaration: declare the object (object name / object type) and inform the compiler about the object / attribute


  7. Instantiation: the process of creating objects from classes


  8. Initialization: the process of allocating memory space for a variable and determining its initial value


  9. Construction method: a special method with the same name as the class and create an object


  10. Constructor: a special method with the same name as a class, creating an object



2. Bean life cycle: 1 instantiation, 2 attribute assignment, 3 initialization, 4 use, 5 destruction


  1. Pre instantiation stage: execute the post process before ln station method of the instance aware bean postprocessor adapter


  2. Execute the determine candidate constructors method of the instance aware bean postprocessor adapter


  3. Post process merged bean definition method of interface merged bean definition postprocessor


  4. Instantiate bean (execute bean construction method)


  5. Post instantiation stage: execute the post process after in station method of the instance aware bean postprocessor adapter. When the method returns false, the subsequent pre-processing of bean attribute assignment and bean attribute assignment will be skipped,


  6. Stage before attribute assignment (the value of the attribute can be modified here): execute the post process properties method of the instance aware bean postprocessor. When null is returned, it means that the bean does not need to set properties. It returns directly to the next stage.


  7. Attribute assignment (populate)


  8. Aware interface


  9. Execute the post process before ln it I alignment method of the instance aware bean postprocessor adapter


  10. Custom initialization method


  11. Execute the post process after ln it I alignment method of the instance aware bean postprocessor adapter


  12. Container created successfully, available for use


  13. Call custom destroy method



3. Bean tag attribute

  1. ID attribute: unique and non repeatable
    The attribute value can be named arbitrarily, but can not contain Chinese and special characters.
    The configuration object is obtained according to the value of the ID attribute.

  2. Class attribute: the full path name of the class
    The full path name of the class where the object is created.

  3. Name attribute: cannot be repeated
    The function is consistent with the ID. Basically no longer used.
    Difference: the ID attribute value cannot contain special characters, and the name attribute value can contain.

  4. Scope attribute
    Bean scope attribute value:



Value range
Singleton single case Default value: only 1 instance is generated
Multiple cases of prototype Multiple cases
request In the web project, spring creates a bean object and stores the object in the request field
session In the web project, spring creates a bean object and stores the object into the session domain
global session In the web project, the application is in the portlet environment. If there is no portlet environment, the global session is equivalent to the session
  1. Scope: scope

    Singleton: Singleton mode. In the whole spring IOC container, only one instance will be generated by the bean of singleton scope.
     Prototype: a new bean instance will be generated every time the bean of the prototype scope is obtained through the getBean () method of the container.
     Request: for an HTTP request, the bean in the request scope will only generate one instance, which means that in the same HTTP request, the program will always get the same instance every time it requests the bean. This scope is really effective only when spring is used in web applications.
     Session: this scope limits the definition of beans to HTTP sessions. Valid only in the context of Web aware spring ApplicationContext.
     Global session: each global HTTP session corresponds to a bean instance. In a typical case, it is only valid when using portlet context, and it is also valid only in web applications.

4. Spring core:

  1. Spring container interface: ApplicationContext

    Classpathxmlapplicationcontext: search the configuration file from the class loading path and create a spring container based on the configuration file.
     Filesystemxmlapplicationcontext: search the configuration file from the relative path or absolute path of the file system, and create a spring container based on the configuration file.

4. Bean instantiation: no parameter, factory static, factory instance

1. Instantiation of parameterless construction method: default

/*Rewrite parameterless construction - modify the default construction method - corresponding interface*/
public UserDaoImpl(){
    System. out. Println ("nonparametric construction modification: userdaoimpl object creation...);
}

2. Factory static method instantiation: directly call the method

public class StaticFactory {
    /*Object factory - object creation - return object*/
    public static UserDao getUserDao() {
        /*Return object*/
        return new UserDaoImpl();
    }
}

3. Factory instance method instantiation: first have the factory object and then adjust the method

public class DynamicFactory {
    /*Object factory*/
    public UserDao getUserDao() {
        /*Return object*/
        return new UserDaoImpl();
    }
}

5. Dependency injection Di: injection type: object, common data, and collection data

1. Construction method: parametric structure

Public userserviceimpl (userdao userdao) {/ * parameterized structure*/
        this.userDao = userDao;
    }

2. Set method injection:

private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save() {
        userDao.save();
    }

3. P namespace injection: (set)

1. Import P namespace:

xmlns:p="http://www.springframework.org/schema/p"

2. Modify the injection method:

6. Dependency injection type: reference data (object), general data, and collection data

1. General data

private String username;
    private int age;


    public void setUsername(String username) {
        this.username = username;
    }

    public void setAge(int age) {
        this.age = age;
    }
/*Get file stream*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*Interface * // * interface implementation*/
        UserDao ud = (UserDao) app.getBean("userDao11");
       /*Get object * // * strong conversion object*/
       
        Object ud1 = app.getBean("userDao11");
        
        ud.save();

2. Reference data

3. Aggregate data

/*Define variables and construction methods*/
    private List strList;
    private Map userMap;
    private Properties properties;

    public void setStrList(List strList) {
        this.strList = strList;
    }

    public void setUserMap(Map userMap) {
        this.userMap = userMap;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }


   	/*Method of class implementing interface*/
    public void save() {
        System.out.println(strList);
        System.out.println(userMap);
        System.out.println(properties);
    }
private String name;
    private String addr;

    public String getName() {
        return name;
    }

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

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
let
                bright
                let
            
        
        
            
                 
                 
            
        
        
            
                111
                1112
                1113
/*Get file stream*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*Interface * // * interface implementation*/
        UserDao u2= (UserDao) app.getBean("userDao222");
       /*Get object * // * strong conversion object*/
       
        Object d2 = app.getBean("userDao222");

        u2.save();

3、 Introduce other configuration files (sub module development)

In the actual development, there are many spring configuration contents, which leads to the complexity of spring configuration, which can be split into other configuration files
And the spring main configuration file is loaded through the import tag

1. < import > label

applicationContext.xml
applicationContext-product.xml
applicationContext-user.xml

4、 Key configuration of spring

1. < property > tag: Property injection, setter ()

Property: injected through the corresponding method of setter.

Tags: attribute injection
	Name attribute: attribute name
	Value attribute: the injected ordinary attribute value
	Ref attribute: injected object reference value
	label
	label
	label

one Name attribute: attribute name

one Value attribute: the injected ordinary attribute value

one Ref attribute: injected object reference value

one < Set > label: Set – Reference ref

one < List > tag: Set – Reference ref

people
	            civil
	            people

one < Map > tag: Set – key value pair

one < Properties > tag: similar to map – key value pair

111
                1112
                1113

2. < constructor Arg > label: Specifies the parameter injection of the constructor

Constructor Arg: injected by constructor.

The constructor Arg attribute calls the corresponding constructor by specifying the type,

soldier
            scientist
            pilot

5、 Spring API

1. Inheritance of ApplicationContext

ApplicationContext: interface type, which represents the application context. The bean object in the spring container can be obtained through its instance.

2. Implementation class of ApplicationContext

1. Classpathxmlapplicationcontext: classpath file type application context – files under resource (relative)

It loads the configuration file from the root path of the class (commonly used)
/*Get file stream*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*Interface * // * interface implementation*/

Applicationsystemcontext – absolute file system path

It is to load the configuration file from the disk path, and the configuration file can be anywhere on the disk.
ApplicationContext appp = new FileSystemXmlApplicationContext("C:\\Users\\REMLI\\IdeaProjects\\REM_SSMS\\src\\main\\resources\\applicationContext.xml");

3. Annotationconfigapplicationcontext: annotation configuration application context – annotation development

When configuring container objects with annotations, you need to use this class to create a spring container. It is used to read annotations.

3. Use of getBean () method

1. Forced rotor type

One is to obtain through ID: there can be more than one type, and forced conversion is required after obtaining.
UserDao u111= (UserDao) appp.getBean("userDao222");

2. Get class object directly: directly specify the class file

One is obtained through the return value: there can only be one type, and no forced conversion is required after obtaining.
UserDao userDao = app.getBean(UserDao.class);

3. Get through Java object

Object d111 = appp.getBean("userDao222");

6、 Configure data source

1. Role of data source (connection pool)

1. Improve program performance

2. Instantiate the data source and initialize some connection resources in advance

3. Get from the data source when using connection resources

4. Return the connected resources to the data source after use

Common data sources: DBCP, c3p0, bonecp, Druid, etc

2. Introduce related coordinate dependency

org.springframework
        spring-context-support
        5.3.7
    
    
        mysql
        mysql-connector-java
        8.0.19
    
    
    
        com.alibaba
        druid
        1.1.10
    
    
        c3p0
        c3p0
        0.9.1.2
    
    
        junit
        junit
        4.12

3. Manually create c3p0 data source: be sure to pay attention to spaces and correct names

@Test
    /*Test manually creating c3p0 data sources*/
    public void test1() throws Exception {
        /*Create data source*/
        /*Campopol*/
        /*One problem to note is to ensure the correctness of MySQL statements. MySQL 8.0.19 is slightly different from the connection statements of previous versions*/
        /*Instantiate object*/
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        /*Object calls method and assigns value to set method*/
        /*Assignment driven class database connection information*/
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/remli?useSSL=false&serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("2020");
        
        /*Create object to get connection information*/
        Connection connection = dataSource.getConnection();
        
        /*Print object information*/
        System. out. Println ("\ naddress:" + connection);
        
        /*Connection closing and resource return*/
        connection.close();

    }

4. Manually create Druid data source: be sure to pay attention to spaces and correct names

@Test
    /*Test manual creation of Druid data source*/
    /*If druiddatasource cannot be found, please clean up the jar package in clean in Maven*/
    public void test2() throws Exception {
        /*Create data source*/
        /*One problem to note is to ensure the correctness of MySQL statements. MySQL 8.0.19 is slightly different from the connection statements of previous versions*/
        /*Instantiate object*/
        DruidDataSource dataSource = new DruidDataSource();
        
        /*Object calls method and assigns value to set method*/
        /*Assignment driven class database connection information*/
        dataSource. setDriverClassName("com.mysql.cj.jdbc.Driver");/* Coupling exists*/
        dataSource. setUrl("jdbc: mysql://localhost:3306/remli?useSSL=false&serverTimezone=UTC "); / * coupling exists*/
        dataSource. setUsername("root");/* Coupling exists*/
        dataSource. setPassword("2020");/* Coupling exists*/
        
        /*Create object to get connection information*/
        DruidPooledConnection connection = dataSource.getConnection();
       
        /*Print object information*/
        System.out.println(connection);
        
        /*Connection closing and resource return*/
        connection.close();
    }

5. Manually build c3p0 (load the properties configuration file): note that the space and name are correct

1. Create code:

@Test
    /*Test manually creating c3p0 data source (loading properties configuration file)*/
    public void test3() throws Exception {
    
        /*Read configuration file*/
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");

        /*Create data source object and set connection parameters*/
        /*Campopol*/
        /*One problem to note is to ensure the correctness of MySQL statements. MySQL 8.0.19 is slightly different from the connection statements of previous versions*/
        /*Instantiate object*/
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        /*Object calls method and assigns value to set method*/
        /*Assignment driven class database connection information*/
        /*Note that values cannot be enclosed in double quotes*/
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);

        /*Create object to get connection information*/
        Connection connection = dataSource.getConnection();

        /*Print object information*/
        System. out. Println ("\ naddress:" + connection);

        /*Connection closing and resource return*/
        connection.close();

    }

2. Configuration file JDBC Properties: pay attention to correct statements, spaces and names

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/remli?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=2020

7、 Spring configuration data source: datasource – Set method injection

Give the right to create the datasource to the spring container
Datasource parameterless construction method - spring instantiates the object by default through the parameterless construction method
Use datasource to obtain the connection object of the database - you need to set the database connection information through the set method - spring can inject strings through the set method

1. Application configuration file: configure connection information – com mchange. v2. c3p0. ComboPooledDataSource

1. Pay attention to a question: & will report an error – write it as & amp

2. Replace combopooleddatasource – > classpathxmlapplicationcontext

@Test
    /*Test the spring container to generate data source objects (load the application.xml configuration file)*/
    public void test4() throws Exception {
        /*Read configuration file*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        /*Create data source object and set connection parameters*/
        /*Instantiate object*/
        DataSource dataSource4 = app.getBean(DataSource.class);

        /*Create object to get connection information*/
        Connection connection4 = dataSource4.getConnection();

        /*Print object information*/
        System. out. Println ("\ naddress:" + connection4);

        /*Connection closing and resource return*/
        connection4.close();

    }

VIIISpring configures the data source separately: XML loads the properties file — separating the database from spring

The key value pairs of properties should be written in such a way that the key names are not the same!!!
Respective databases - load - corresponding properties files

1. Steps for spring to load the properties file:

1. Introduce context namespace and constraint path:

applicationContext. Loading jdbc.xml Properties configuration file -- get connection information
First, introduce the context namespace and constraint path:

1 namespace: xmlns: Context=“http://www.springframework.org/schema/context

There are components in the context namespace to scan and load external Label of the properties file
Loaded into IOC The properties file can be obtained through a spring El expression in the form of ${key name}

: configure component scanning to scan the annotations under the specified package
: load external Properties file into the spring container,
You can get values through spel, that is, ${}, such as configuring database connection parameters
xmlns:context="http://www.springframework.org/schema/context"

2 constraint path:http://www.springframework.org/schema/context

Constraint path 1: http://www.springframework.org/schema/context                      
Constraint path 2: http://www.springframework.org/schema/context/spring-context.xsd

The XML document needs to be verified when spring starts. The function of the constraint is to verify the correctness of the XML document syntax of the configuration file.
http://www.springframework.org/schema/context/spring-context.xsd

2. Load configuration file label: < context: Property placeholder location = “XX. Properties” / >

: load external Properties file into the spring container,
You can get values through spel, that is, ${}, such as configuring database connection parameters

3. < property name = “” value = “${key}” / >: SPR language – El

Get key value – get the name value corresponding to properties

4.DataSource.class

@Test
    /*Test the spring container to generate data source objects (load the application.xml configuration file)*/
    public void test4() throws Exception {
        /*Read configuration file*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        /*Create data source object and set connection parameters*/
        /*Instantiate object*/
        DataSource dataSource4 = app.getBean(DataSource.class);

        /*Create object to get connection information*/
        Connection connection4 = dataSource4.getConnection();

        /*Print object information*/
        System. out. Println ("\ naddress 4:" + connection4);

        /*Connection closing and resource return*/
        connection4.close();

    }

5.DruidDataSource.class

@Test
    /*Test the spring container to generate data source objects (load the application.xml configuration file)*/
    public void test5() throws Exception {
        /*Read configuration file*/
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        /*Create data source object and set connection parameters*/
        /*Instantiate object*/
        DruidDataSource dr = app.getBean(DruidDataSource.class);

        /*Create object to get connection information*/
        Connection connection5 = dr.getConnection();

        /*Print object information*/
        System. out. Println ("\ naddress 5:" + connection5);

        /*Connection closing and resource return*/
        connection5.close();

    }
The two cannot be opened at the same time and will report errors to each other

Summary: namespace modification method, assign the URL after xmlns, change beans to context, and then create a new xmlns: context.
Copy the previous paragraph XSI: schemalocation, change all beans to context and add them later.
Import file path. Classpath indicates the path of class file. Resource file is saved in classpath file by default,
So the path is "classpath: JDBC. Properties".
Call the properties file in XML and use El expressions.

Problem record:
	Druid reports an error after importing properties:
		[create connection SQLException, 
		url:jdbc:mysql://localhost:3306/demo, errorCode 1045, state 28000]

Error reason: the name in the properties configuration file conflicts with the driud property name.

Before modification:
	driver=com.mysql.cj.jdbc.Driver
	url=jdbc:mysql://localhost:3306/remli?useSSL=false&serverTimezone=UTC
	username=root
	password=2020

After modification:
	jdbc.driver=com.mysql.cj.jdbc.Driver
	jdbc.url=jdbc:mysql://localhost:3306/remli?useSSL=false&serverTimezone=UTC
	jdbc.username=root
	jdbc.password=2020

9、 Spring annotation development

Semantic: see the name and know the meaning

1. Spring original annotation

The original spring configuration mainly replaces the configuration

@Component — ID — instantiation — whatever — no semantics

Used on classes to instantiate beans
This component is used for spring to generate a bean - > component: component
Component: component byid
@Component ("userdao") / * is equivalent to configuration file ID and location class*/
@Component ("userservice") / * is equivalent to configuration file ID and location class*/

@Controller – web layer control class instantiation – semantic

Used on Web tier classes to instantiate beans
This controller is used for spring to generate a bean

@Service – service layer service class instantiation – semantic

Used on the service layer class to instantiate beans
This business logic class is used for spring to generate a bean
@Service ("userservice") / * is equivalent to configuration file ID and location class*/

@Repository – ID – Dao layer data storage class instantiation – semantic

Used on Dao layer classes to instantiate beans
This Dao class is used for spring to generate a bean - > Repository: repository data encapsulation base
Repository: storeroom byid
@Repository ("userdao") / * is equivalent to configuration file ID and location class*/
@Controller
@Service
@Repository
@Component
There is no essential difference between them
They exist to distinguish the web, service and Dao layers
Facilitate code reading.

@Autowired — no setter required — field injection by type — can be used alone

type
使用在字段上用于根据type依赖注入
Function: automatically encapsulate the attribute, or field
It can be received without setter method

Single class: used alone
@Autowired
    //Single use - inject from the spring container according to the data type matching. Note that a single data class can be identified and multiple data classes cannot be identified
Used with @ qualifier:
@Autowired
    	//Single use -- inject by matching from spring container according to data type
    	//Note that a single data class can be identified and multiple data classes cannot be identified
    @Qualifier("userDao")
		//Match from container by ID
		//But it needs to be used with @ Autowired here

@Qualifier — name / ID — @ Autowired + inject by name — must be used together

id+name
Used in conjunction with @ Autowired for dependency injection by name
Match the XXX attribute according to the modifier @ qualifier ('xxx ') - > provided,
This annotation must be used in conjunction with autowire,
Qualifier: modifier byname
	@Autowire 
	@Qualifier("user") 
	Meaning: the bean encapsulating the user annotation is a member of this class object. Byname is injected according to the name and set on the field 

	@Qualifier is often used in parameter assignment
	For example: string GetUserName (@ qualifier ("user") user) {}


Used with @ qualifier:
@Autowired
    	//Single use -- inject by matching from spring container according to data type
    	//Note that a single data class can be identified and multiple data classes cannot be identified
    @Qualifier("userDao")
		//Match from container by ID
		//But it needs to be used with @ Autowired here
@Autowired
    @Qualifier("userDao")

@Resource — inject by name = @ Autowired + @ qualifier — provided by J2EE

Equivalent to @ Autowired + @ qualifier, injected by name
Resource is a combination of aotuwire annotation and qualifier [email protected] Resource ("user"), a bean labeled user

@Resource ("user") the bean encapsulating the user annotation is a member of the benlei object 	== 
	@Autowire 
	@Qualifier
	
By default, it is injected according to the name dependency,

Default resource () = resource like resource (name = "XXX") - > reflects the idea of object-oriented
Should be set on the field

It can be manually set to inject resources according to the type (type = user. Class) - > reflect the object-oriented idea
It should be set on the set method
@Resource(name="userDao")
    	//Equivalent to @ Autowired + @ qualifier ("userdao")

@Value — inject common attribute

Inject common attributes
@Value("xxx"); Assign a value to the decorated field;
	It is usually used in conjunction with spiel (spring expression language)

@Value("${jdbc.url}") private String url;  Assign value to URL
	——>(the value corresponding to jdbc.url in the properties suffix file introduced in spring) 
	——>Or {jdbc.url value in propertyroute annotation}
@Value ("value injection succeeded") // attribute value injection
    private String vals;


    @Value ("${JDBC. Driver}") // database attribute value injection
    private String sjk;

@Scope – bean scope

Label the scope of the bean
Common: 	@ Scope ("Singleton") declares the bean of this class obtained from the spring container
				Yes and only one (singleton mode)
				
		@Scope ("prototype") declares the bean of this class obtained from the spring container
				There are multiple (standard bean pattern)
@Scope ("prototype") // multiple cases
//@Scope ("Singleton") // single example

@Postconstruct — bean initialization method — after construction

Use to label the method, which is the initialization method of bean
Annotations are used before user-defined initialization methods,
Declare that this method is the initialization method of this class
@Postconstruct: it means that after the construction method is executed, the construction method creates an object, and the object calls the initialization method
@PostConstruct
    public void init(){
        System. out. Println ("service object initialization method");
    }

@Predestroy – bean destruction method – before destruction

Use to mark the method as the destruction method of bean
The annotation is used before the user-defined end method,
Declare that this method is the end method of this class,
Call this method before the current object is destroyed
@PreDestroy ; When the spring container is destroyed, execute
@PreDestroy
    public void destory(){
        System. out. Println ("service object destruction method");
/// * read configuration file*/
/// * subclass implements the destruction method - close manually*/
//        ClassPathXmlApplicationContext apps = new ClassPathXmlApplicationContext("applicationContext.xml");
//
/// * create data source object and set connection parameters*/
/// * instantiate object*/
//        XXX drs = app.getBean(XXX.class);
//
/// * manual shutdown*/
//        drs.close();
    }

@Order — injection object reference collection

When injecting a collection of object references:
@Order(1) 
@Order (2) means that the beans generated by this class will be stored in a list and inserted into the list in order

If it's a map, the order has nothing to do with it,
However, the map must be defined as string to receive the ID value of the corresponding object (ID unique - > key unique);

The list and map here can be injected through @ Autowired or @ resource;

2. Component scan: component scan

Note: during annotation development, it needs to be in ApplicationContext Configuring component scanning in XML
Function: specify which package and the beans under it need to be scanned to identify the classes and methods configured with annotations
Package: basic package + including sub packages

3. Comparison of two configuration / annotation methods:

1. Original XML configuration method

public interface UserDao {
    public void start();
}
public class UserDaoImpl implements UserDao {
    public void start(){
        System. out. Println ("start program 1 ·········");
    }
}
public interface UserService {
    public void start();
}
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    /*Setter method*/
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
    
    public void start(){
        System. out. Println ("program startup 2 ······");
    }
}
public class UserController {

    public static void main(String[] args) {

        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = app.getBean(UserService.class);

        userService.start();
    }

}

2. Annotation @ method!!!

public interface UserDao {
    public void start();
}
/*XML configuration location class file location*/
/*

*/

/*Annotation*/
/*
@component
*/

@Component ("userdao") / * is equivalent to configuration file ID and location class*/
public class UserDaoImpl implements UserDao {
    public void start(){
        System. out. Println ("start program 1 ·········");
    }
}
public interface UserService {
    public void start();
}
/*XML configuration location class file location*/
/*

*/


/*Annotation*/
/*
@component
*/

@Component ("userservice") / * is equivalent to configuration file ID and location class*/
public class UserServiceImpl implements UserService {

    /*XML configuration injection properties*/
    /*
    
    */

    /*Annotation - Injection*/
    /*
    @Autowired
    @Qualifier("userDao")
    */

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    /*Setter method*/
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }

    public void start(){
        System. out. Println ("program startup 2 ······");
    }
}
public class UserController {

    public static void main(String[] args) {

        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = app.getBean(UserService.class);

        userService.start();
    }

}

2. Spring new annotation

@Configuration — specify the class as the spring configuration class

Used to specify that the current class is a spring configuration class, and annotations will be loaded from this class when the container is created

@Componentscan — specifies the spring initialization container scan package

Used to specify the package that spring will scan when initializing the container
Function and in the XML configuration file of spring

equally

Componentscan: component scan bypackage componentscan: it is very important when using full annotation If it is not configured, spring's IOC container will not scan any packages by default, and there will be no beans

@Bean — the return value of the method is stored in the spring container

On a method, the annotation stores the return value of the method in the spring container

@Propertysource — load the properties configuration file

For loading Configuration in the properties file

@Import — import other class configurations

Used to import other configuration classes

3. Spring object creation – instantiation – find the location of the class creation object

@Component — random

Define beans, which can be used when it is difficult to classify

@Controller — Web view control layer

@Controller ("name of bean")
Define the control layer bean, such as action

@Service – business service layer

@Service ("name of bean")
Define business tier beans

@Repository — Dao data persistence layer

@Repository ("name of bean")
Defining Dao layer beans

4. Spring injection

1. Object injection: basis, bean (ID) = name, class and attribute injection

@Resource: byname injection by default – (J2EE provides annotation) — its dependency needs to be added

Spring resolves the name attribute of the @ resource annotation to the name of the bean, while the type attribute resolves to the type of the bean.
By default, injection is assembled by name. Only when no bean matching the name is found will injection be performed by type.
It has two important attributes:
If you want to reduce your dependence on spring, it is recommended to use the @ resource method.
javax.annotation
        javax.annotation-api
        1.3.2
    
    
    
        javax.annotation
        jsr250-api
        1.0
1Name: Spring resolves the attribute value of name into the name of the bean and uses the automatic injection strategy of byname

2type: Spring resolves the attribute value of type to the type of bean and uses the automatic injection strategy of bytype

3 reflection – byname auto injection strategy
If neither the name attribute nor the type attribute is specified, spring uses the byname auto injection policy through the reflection mechanism


@Resource assembly sequence:
	If both the name attribute and the type attribute are specified, spring will find a unique matching bean from the container for assembly, and throw an exception if it cannot be found
	If the name attribute value is specified, the bean with matching name will be found in the container for assembly. If it is not found, an exception will be thrown
	If the value of the type attribute is specified, the only bean with matching type will be found in the container for assembly. If it cannot be found or multiple beans are found, an exception will be thrown
	If none is specified, the assembly will be carried out automatically in byname mode. If there is no matching, the original type will be returned for matching. If there is matching, the assembly will be carried out automatically

@Autowritten: default bytype injection

The default is assembly injection by type,
By default, it requires that dependent objects must exist. If null value is allowed, you can set its required to false.
If we want to assemble by name, we can add a @ qualifier annotation.

@The Autowired interface can only have one implementation class, which is injected by bytype
By default, dependent objects must exist. If you want to allow null values, you can set its required property to false, such as @ Autowired (required = false)
@Autowried
	@Qualifier("adminDAO")
	private AdminDAO adminDAO;

@Qualifier: default class name

The annotation of spring is injected by name. Generally, when there are two or more beans, I don't know which one to inject, which is used as the decoration of @ autowired()
@The qualifier interface can have multiple implementation classes, which can be injected according to the class name of the implementation class

2. Common attribute injection: — value

Usually, instead of direct assignment, it calls the imported properties file for assignment.
As long as the core class or the introduced subclass introduces the properties file, you can directly use El expression.
Import expression in El format

Use @ value to dynamically inject external values into beans. Usage:
	Inject normal string
	Inject operating system properties
	Injection expression result
	Inject other bean attributes: inject another attribute of beaninject object
	Inject file resources
	Inject URL resources
@Value("${jdbc.username}")
	private String name;
@Value("normal")
    private String normal; //  Inject normal string

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; //  Inject operating system properties

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; // Injection expression result

    @Value("#{beanInject.another}")
    private String fromAnotherBean; //  Inject other bean attributes: inject another attribute of beaninject object. See the following for the specific definition of the class

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; //  Inject file resources

    @Value("http://www.baidu.com")
    private Resource testUrl; //  Inject URL resources

Recommended Today

Golang influxdb basic operation

Infixdb basic operation Basic operation connect [[email protected] ~]# influx -precision rfc3339 Connected to http://localhost:8086 version 1.8.0 InfluxDB shell version: 1.8.0 > precisionThe parameter indicates the format and precision of any returned timestamp. In the above example,rfc3339Yes, let influxdb returnRFC339Timestamp of format (yyyy-mm-ddthh: mm: SS. Nnnnnnnz). validate logon > auth username: icms password: [email protected] Operation database […]