Review spring to review

Keywords: Java Spring Spring Boot

Review the basic use of spring

As the saying goes: knives don't need to rust after a long time, but knowledge can also be lost after a long time. This article reviews the basic use of spring.

concept

spring is a lightweight container (framework) for control inversion (IoC) and face-to-face (AOP)

IOC: Control reversal refers to the transfer of control over the creation of objects to the Spring framework for management, and Spring creates instances based on configuration files and manages dependencies between instances. Loose coupling between objects also facilitates the reuse of functions.

AOP: Aspect-oriented, an object-oriented complement to extract and encapsulate common behaviors and logic that are business-independent but affect multiple objects into a reusable module. This module is named "slice". It reduces duplicate code in the system, reduces coupling between modules, and improves maintainability of the system. It can be used for privilege authentication, logging, transaction management.

Advantage:

  • spring is a low-invasive design with low code contamination
  • spring's DI mechanism handles the dependencies between objects to the framework, reducing the coupling of build
  • spring provides integration support for mainstream application frameworks

Use

A simple demonstration

  1. Create a springboot project

  2. Suppose there is such an interface under dao:

    package com.lys.dao;
    
    public interface dbDao {
        void use();
    }
    

    There are two classes that implement the above interface:

    package com.lys.dao.dbimpl;
    
    import com.lys.dao.dbDao;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class OracleImpl implements dbDao {
        @Override
        public void use() {
            System.out.println("Oracle data base");
        }
    }
    
    package com.lys.dao.dbimpl;
    
    import com.lys.dao.dbDao;
    import org.springframework.stereotype.Repository;
    
    //The name of the automatic default bean is lowercase
    @Repository("mysql")// Name of custom bean s
    public class MySQLImpl implements dbDao {
        @Override
        public void use() {
            System.out.println("mysql data base");
        }
    }
    
  3. Getting object instances of classes in real use

    There are several ways to get it, either through a custom name, class name.class, or the default bean name, as follows;

    @SpringBootTest
    class Spring12ApplicationTests implements ApplicationContextAware {
        private ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext=applicationContext;
        }
    
        @Test
        public void test1(){
            //Mode 1: Use a custom name for the bean
            //MySQLImpl mySQL = (MySQLImpl) applicationContext.getBean("mysql");
    
            //Mode 2: Use the default name of the bean (that is, lowercase first letter of the class name)
            //MySQLImpl mySQL = (MySQLImpl) applicationContext.getBean("mySQLImpl");
    
            //Mode 3: Specify the bean type using the class name.class
            MySQLImpl mySQL =applicationContext.getBean(MySQLImpl.class);
            mySQL.use();
        }
    }
    

4. Actually, the process of getting the bean object can be further simplified. Automatic assembly can be achieved through @Autowired. The above tests can be simplified as follows:

@SpringBootTest
class Spring12ApplicationTests implements ApplicationContextAware {
    @Autowired
    private MySQLImpl mySQLImpl;
    
    @Test
    public void test1(){
        mySQL.use();
    }
}

5. How do you register beans when referencing third-party libraries? You can write a configuration class with a comment @confuguration to indicate that this is a special class in which you can customize the type of beans returned with @Bean

Give an example:

package com.lys.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

@Configuration
public class AlphaConfig {
    @Bean
    public SimpleDateFormat simpleDateFormat(){
        //Register a time-formatted bean instance here
        return new SimpleDateFormat("yyyy-MM-dd");
    }
}

Called as needed:

package com.lys;
import java.text.SimpleDateFormat;
import java.util.Date;

@SpringBootTest
class Spring12ApplicationTests implements ApplicationContextAware {
    @Autowired
    private SimpleDateFormat simpleDateFormat;

    @Test
    public void test3(){
        System.out.println(simpleDateFormat.format(new Date()));
    }
}

Common Spring Notes

Note Namefunction
@ControllerIdentify this class as the spring MVC controller processor used to create http request objects
@RestControlleReturning json in @Controller requires @ResponseBody to work with. If you directly replace @Controller with @RestController, you no longer need to configure @ResponseBody, which returns json format by default.
@ServiceUsed to mark business tier components
@AutowiredWrite on fields or methods to assemble bean s
@RepositoryUsed to label the data access component, the Dao component
@componentWhen components are not well categorized, you can use this comment to generically refer to components
@ScopeScope used to identify a bean
@QualifierWhen creating multiple beans of the same type, you can use the @Qualifier and @Autowired annotations to indicate which real beans to use to assemble, eliminating confusion that may arise during assembly.
@RequestMappingProvide preliminary request mapping information
@RequestParamParameters used to map request parameter area data to functional processing methods
Wait...

Posted by yogadt on Wed, 20 Oct 2021 09:13:07 -0700