spring Notes

Spring

Introduction

Boot: conventions are larger than configurations, boot allows rapid development of individual microservices
cloud: boot-based

I. IOC

1.1 Control Inversion

  1. IOC Control Reverse

Control: Objects are no longer programmed to new newer, but handed over to spring
Reverse: Instead of creating objects, the program itself becomes a passive recipient

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring-learn</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>
</project>

1.1 DI Dependent Injection

  1. Constructor Injection
    Reversal:

DI Dependent Injection is a way to implement IOC

public interface GetStudentDao {
    void getStudent();
}
public class GetStudentDaoImpl implements GetStudentDao{
    @Override
    public void getStudent() {
        System.out.println("call getstudentdao");
    }
}

//service layer
public interface GetStudentService {
    void getStudent();
}

public class GetStudentServiceImpl implements GetStudentService {

    private GetStudentDao g = new GetStudentDaoImpl();

//    public void setDao(GetStudentDao dao){
//        g = dao;
//    }
    @Override
    public void getStudent() {
        g.getStudent();
    }
}

Without the setDao method, going directly to new will result in code modifications if you want to add a dao implementation.
Therefore, using the set method is just in line with the fact that abstraction depends on concrete rather than on abstraction, which is also the IOC's idea of delaying the loading of classes.

  1. set mode injection (focus)
  2. Extended Injection
  3. Scope of bean s

Automatic assembly of 1.2 bean s

1 autowired ,Qualifier
2 byName,byType

1.3 Note Development

  1. bean
  2. How attributes are injected

1.4 Configure bean s by configuring classes

2. AOP

2.1 Static Proxy

public interface Rent1 {
    void rent();
}
//Real Role
public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("Real object rental house");
    }
}

Writing of static proxy classes

//delegable role
public class Proxy implements Rent{
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void see(){
        System.out.println("Take customers to view housing sources");
    }

    @Override
    public void rent() {
        see();
        host.rent();
        contact();
    }
    public void contact() {
        System.out.println("Sign a contract");
    }
}

See from the code above that proxy roles depend on real roles

Test Code

public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

2.2 Dynamic Proxy

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler implements InvocationHandler{
    //Agented Interface
    private Object target;

    //Injection Agent Interface
    public void setTarget(Object target){
        this.target = target;
    }

    //Generate Proxy Class
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }
    //Process the proxy instance and return the results
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }
    public void log(String msg ){
        System.out.println("implement " + msg + "Method");
    }
}

Test Code

/**
 * The benefits and responsibilities of the agent model are clearer.
 * Real roles have fewer business categories, while proxy roles do what proxy roles do
 */
public class Client {
    public static void main(String[] args) {
        /**
         * Main design InvocationHandler, Proxy
         */

        Host host = new Host();//Role of Real Agent
        //Agent Role Runtime Creation
        ProxyInvocationHandler  hander = new ProxyInvocationHandler();
//       //Set proxy object
        hander.setTarget(host);
        //Generate dynamic proxy classes
        Rent1 proxy = (Rent1) hander.getProxy();
        proxy.rent();
    }
}

During the experiment, java.lang.ClassCastException (java cast exception) was encountered
I use Rent under other packages in dynamic proxy classes to cause type inconsistency, so programming must be careful, careful, and more careful!!!

2.3 AOP Principles

aop facet programming, a new idea, in the process of program execution, dynamically packages a program so that it does not change
On the original program, add function
What does it have to do with oop?
https://blog.csdn.net/qukaiwei/article/details/50367761
https://blog.csdn.net/weixin_44207403/article/details/106736102
spring-jdbc org.aspectj
mybatis-spring

12.2 mybatis configuration steps

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="pojo"/>
    </typeAliases>
<!--    Set up-->
<!--    <settings>-->
<!--        <setting name="" value=""/>-->
<!--    </settings>-->


<!--    <environments default="development">-->
<!--        <environment id="development">-->
<!--            <transactionManager type="JDBC"/>-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!--                <property name="url" value="jdbc:mysql://localhost:3306/CMS?characterEncoding=utf-8&amp;serverTimezone=UTC&amp;useSSL=true"/>-->
<!--                <property name="username" value="root"/>-->
<!--                <property name="password" value="12345678"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
<!--    </environments>-->

<!--    <mappers>-->
<!--        <mapper class="dao.StudentDao"/>-->
<!--    </mappers>-->
</configuration>

Test Code

    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession(true);
    StudentDao mapper = session.getMapper(StudentDao.class);

12.3 spring-batis

  1. Write Data Configuration Source
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    spring take over mybatis,
            DataSource:Use Spring Data Source Replacement mybatis Configuration, c3p0 dbcp druid
            Spring Provided JDBC:  org.springframework.jdbk.datasource
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/CMS?characterEncoding=utf-8&amp;serverTimezone=UTC&amp;useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="12345678"/>
    </bean>

    <!--    sqlSessionFacotry-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        binding mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:dao/StudentDao.xml"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--        Constructor injection only sqlSessionFactory -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!--    spring Configure Transactions-->
    <!--    step1 Create a DataSourceTransactionManager object-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg index="0" ref="dataSource"/>
        <!--        <property name="dataSource" ref="dataSource"/>-->
    </bean>

    <!--    step2 Delegate transaction to container management-->
    <!--    Combination AOP Implement transaction weaving-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--        Configure properties for those methods-->
        <!--        Configure the propagation characteristics of transactions, default REQURED-->
        <tx:attributes>
            <tx:method name="query" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--    Configuration transaction entry-->
    <aop:config>
        <aop:pointcut id="txpointcut" expression="execution(* dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/>
    </aop:config>
</beans>
  1. sqlSessionFacotry
  2. sqlSessionTemplate
  3. An implementation class is required for the interface
  4. Injecting implementation classes into spring

spring in two ways
Mode 1: sqlSessionTemplate
Mode 2: Inherit SqlSessionDaoSupport

public class StudentDaoImpl2 extends SqlSessionDaoSupport implements StudentDao

###13 Transactions

13.1 Overview

ACID
A: Atomicity
C: Consistency
I: Isolated
D: Persistence; data overrides classes once transactions are committed

Transaction Management in 13.2 spring

Configure Claim Transactions
Transaction weaving with aop
Configure Transaction Classes
[See #### 12.3 spring-batis]

Keywords: Java Spring Spring Boot

Added by hyperyoga on Wed, 06 Oct 2021 20:42:21 +0300