Spring--quick start

Take the registration driver process when we perform jdbc operations as an example:

Class.forName(“com.mysql.cj.jdbc.Driver”);

DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

From the above code, we can see that com.mysql.cj.jdbc.Driver exists as a string when the first type loads the driver , while the second type imports com.mysql.cj.jdbc.Driver This is a driver class. From the results, the above two statements have realized the group test driver, but in terms of the degree of dependence, the two methods are different, and then we run the test code (do not add mysql-connector-java in pom.xml rely):

public class JdbcDemo1 {

public static void main(String[]args) throws Exception {

//1. Register driver

Class.forName(“com.mysql.cj.jdbc.Driver”);

//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

//2. Get the connection

Connection conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/spring?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false”

,“root”,“520992”);

//3. Obtain the preprocessing object for operating the database

PreparedStatement pstm =conn.prepareStatement(“select * from account”);

//4. Execute SQL and get the result

ResultSet rs=pstm.executeQuery();

//5. Traverse the result set

while(rs.next()){

System.out.println(rs.getString(“name”));

}

//6. Release resources

rs.close();

pstm.close();

conn.close();

}

}

The running results used Class.forName("com.mysql.cj.jdbc.Driver");:

insert image description here

Running results using DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());:

insert image description here

The first method reports an exception at runtime: java.lang.ClassNotFoundException, while the second method directly reports an error that the package does not exist during compilation. Obviously, the first method has more advantages than the second method, reducing the dependence on the package.

As can be seen from the above, the idea of ​​reducing the coupling (decoupling) between programs is:

  • In the first step, use reflection to create objects and avoid using the new keyword

  • Step 2: Obtain the fully qualified class name of the object to be created by reading the configuration file

[](() IOC in Spring


IOC (Inversion of Control, inversion of control). This is the core of spring. IOC is not a technology, but an idea, a design idea to reduce the coupling between programs and optimize programs. Before learning Spring, when we write programs, many dependent objects are often new in our classes, which makes the coupling between programs more and more high.

The so-called IoC, for the spring framework, means that spring is responsible for controlling the life cycle of objects and the relationship between objects.

Spring IOC is responsible for creating objects, managing objects (via dependency injection (DI)), assembling objects, configuring objects, and managing the entire life cycle of these objects. IOC (Inversion of Control) or DI (Dependency Injection) minimizes the amount of application code and makes the application easy to test. Unit testing no longer requires singletons and JNDI lookup mechanisms, and the minimum cost and minimal intrusion are achieved. degree of coupling. The IOC container supports hungry initialization and lazy loading when loading services.

Case: Getting started with xml-based IOC construction

Project directory:

insert image description here

Add the relevant dependencies of the spring framework in pom.xml:org.springframework-spring-context-5.0.2.RELEASE

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

4.0.0

org.example

spring_day01_spring1

1.0-SNAPSHOT

jar

org.springframework

spring-context

5.0.2.RELEASE

Create a business layer interface and implementation class:

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:29

  • Interface of account business layer

*/

public interface IAccountService {

/**

  • demo save account

*/

void saveAccount();

}

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:31

  • The business of the account becomes the implementation class

*/

public class AccountServiceImpl implements IAccountService {

private IAccountDao accountDao=new AccountDaoImpl();

public AccountServiceImpl(){

System.out.println("object created");

}

public void saveAccount() {

accountDao.saveAccount();

}

}

Create the persistence layer interface and implementation class:

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:33

  • Account Persistence Layer Interface

*/

public interface IAccountDao {

/**

  • demo protection account

*/

void saveAccount();

}

/**

  • Account persistence layer implementation class

*/

public class AccountDaoImpl implements IAccountDao {

public void saveAccount() {

System.out.println("saved account");

}

}

Configure the Bean.xml file

<?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/be "Analysis of Java Interview Questions in First-tier Manufacturers + Back-end Development Study Notes + Latest Architecture Explanation Video + Practical Project Source Code Handouts" Free Open Source Prestige Search Official Account【 Programming Advanced Road] ans

http://www.springframework.org/schema/beans/spring-beans.xsd">

Test code:

public class Client {

/*

  • Get the Ioc core container of spring and get the object according to the id

  • Three common implementation classes of ApplicationContext

  • ClassPathXmlApplicationContext: 它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了
    
  • FileSystemXmlApplicationContext: 他可以加载磁盘任意路径下的配置文件(必须有访问权限)
    
  • AnnotationConfigApplicationContext:它是用于读取注解创建容器的
    
  • Problems raised by the two interfaces of the core container:

  • ApplicationContext: This interface is generally applicable to singleton objects

  • When it creates the core container, the strategy used to create the object is to use the immediate loading method, as long as the configuration file is read, the configuration object in the file will be created immediately.

  • BeanFactory: Multiple instance objects apply

  • When it creates the core container, the created object adopts a lazy loading method, when the id gets the object, and when the object is actually created.

*/

public static void main(String[]args){

//1. Get the core container object

ApplicationContext ac=new ClassPathXmlApplicationContext(“bean.xml”);

//ApplicationContext ac=new FileSystemXmlApplicationContext("F:\Intellij idea\spring\spring_day01_spring1\src\main\resources\bean.xml");//The absolute path in the disk corresponding to the configuration file

//2. Get the Bean object according to the id

IAccountService as=(IAccountService)ac.getBean(“accountService”);

IAccountDao ad=ac.getBean(“accountDao”,IAccountDao.class);

/*//------BeanFactory gets the core container object---------

Resource resource=new ClassPathResource(“bean.xml”);

BeanFactory factory=new XmlBeanFactory(resource);

IAccountService as=(IAccountService)factory.getBean(“accountService”);

IAccountDao ad=factory.getBean(“accountDao”,IAccountDao.class);*/

System.out.println(as);

System.out.println(ad);

}

}

operation result:

insert image description here

As can be seen from the results, we did not use new to instantiate the object, but our object has already been instantiated.

[](() instantiates the Bean object


Bean是Spring容器初始化、装配和管理的对象,它是由 spring 来创建的,默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。

Attributes of the label:<bean>

id: Provides a unique identifier for the object in the container. Used to get objects.

class: The fully qualified class name of the specified class. Used to create objects using reflection. The no-argument constructor is called by default.

scope: Specifies the scope of the object.

  • singleton : default value, singleton.

  • prototype : multiple instances.

  • 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 in the session domain.

  • global session: In the WEB project, it is applied in the Portlet environment. If there is no Portlet environment, then globalSession is equivalent to session

init-method: Specifies the name of the initialization method in the class.

destroy-method: Specifies the name of the destroy method in the class.

Three ways to create beans

Project structure:

insert image description here

The first way:根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其它属性和标签时,采用的就是默认函数创建bean对象,此时如果类中没有默认构造函数则对象无法创建。

The second way:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)

/**

  • @Author: Ly

  • @Date: 2020-07-23 23:27

  • Simulate a factory class (this class may exist in the jar package, we cannot provide a default constructor by modifying the source code)

*/

public class InstanceFactory {

public IAccountService getAccountService(){

return new AccountServiceImpl();

}

}

The third method:使用工厂中的静态方法创建对象(使用某个静态方法创建对象,并存入spring容器)

/**

  • @Author: Ly

  • @Date: 2020-07-23 23:27

  • Simulate a factory class (this class may exist in the jar package, we cannot provide a default constructor by modifying the source code)

*/

public class StaticFactory {

public static IAccountService getAccountService(){

return new AccountServiceImpl();

}

}

The scope and life cycle of the bean:

<?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=“accountService” class=“com.ly.service.impl.AccountServiceImpl”

scope=“prototype” init-method=“init” destroy-method=“destroy”>

[](() Dependency Injection


Dependency injection: Dependency Injection, which is the specific implementation of the core IOC of the spring framework.

When our program is written, the object creation is handed over to spring through inversion of control, but it is impossible to have no dependencies in the code. How do we know that the role of IOC is to reduce the coupling between programs, not to eliminate coupling. For the dependencies between the business layer and the persistence layer in our project, we can hand it over to spring for maintenance. When we need to use objects of other classes in our class, spring can provide us with them. The persistence layer object is passed to the business layer through the spring framework, thus saving the steps of our own acquisition.

Dependency injection can inject three types of data:基本类型和string、其他bean类型(在配置文件中或者注解配置过的bean)、复杂类型/集合类型

There are three injection methods at the same time:构造函数提供、set方式提供、注解提供

case:

insert image description here

Constructor injection:

Assign values ​​to member variables by using the constructor in the class. Among them, the assignment operation is not done by ourselves, but through configuration, let the spring framework inject it for us. The specific code is as follows:

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:31

  • The business of the account becomes the implementation class

*/

public class AccountServiceImpl implements IAccountService {

//If it is frequently changing data, it is not suitable for injection

private String name;

private Integer age;

private Date birthday;

public AccountServiceImpl(String name,Integer age,Date birthday){

this.name=name;

this.age=age;

this.birthday=birthday;

}

public void saveAccount() {

System.out.println("The saveAccount method in service has been executed,"+name+","+age+","+birthday);

}

}

set method injection

Provide the set method that needs to inject members in the class for injection. The specific code is as follows:

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:31

  • The business of the account becomes the implementation class

*/

public class AccountServiceImpl2 implements IAccountService {

//If it is frequently changing data, it is not suitable for injection

private String name;

private Integer age;

private Date birthday;

public void setName(String name) {

this.name = name;

}

public void setAge(Integer age) {

this.age = age;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

public void saveAccount() {

System.out.println("The saveAccount method in service has been executed,"+name+","+age+","+birthday);

}

}

Complex type injection:

Dependency injection can inject complex data types, such as s arrays and collections. At the same time, injecting these complex data is also the way of set method injection, but the data types of variables are all collections. The specific code is as follows:

/**

  • @Author: Ly

  • @Date: 2020-07-21 16:31

  • The business of the account becomes the implementation class

Guess you like

Origin blog.csdn.net/tt8889/article/details/124569834
Recommended