A simple guide to get you started with the Spring framework

Introduction

Spring is a popular Java application framework that simplifies Java development and provides a wide range of features and components to enable developers to create enterprise-level applications faster and more efficiently. Before getting started with Spring, we need to have basic knowledge of Java and javaWeb knowledge.

development environment

idea,jdk17

Getting started

Create a class HelloWorld in the project which does nothing except define a method.

package com.example.demo;

public class HelloWorld {
    public void sayHello(){
        System.out.println("hello");
    };
}
复制代码

Create a new configuration file application.xml file in the resources directory

<?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="helloWorld" class="com.example.demo.HelloWorld"/>
</beans>
复制代码

Create a new Application.java class

package com.example.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloWorld helloWorld =(HelloWorld) app.getBean("helloWorld");
        helloWorld.sayHello();
    }
}
复制代码

Then right-click and run in application.java and you can see the output hello

Spring bean definition

Objects managed by the Spring IoC container are called Beans. Beans are created based on information in the Spring configuration file.

<bean id="helloWorld" class="com.example.demo.HelloWorld"/>
复制代码

Common properties

id  The unique identifier of the Bean. The Spring IoC container configures and manages the Bean through this attribute  . The constructor-arg attribute is a sub-element of the bean element. We can pass in the construction parameters through this element to realize the instantiation of the Bean. . The index attribute of this element specifies the sequence number of the construction parameters (starting from 0), and the type attribute specifies the type of the construction parameters. The property attribute is a child element of the bean element and is used to call the setter method in the Bean instance to assign a value to the property, thereby completing the injection of the property. The name attribute of this element is used to specify the corresponding property name in the Bean instance.  The child index of elements such as  ref property and constructor-arg is used to specify a reference to a Bean instance, that is, the id or name attribute in the element.  A child element of elements such as  value property and contractor-arg, used to directly specify a constant value. Scope  represents the scope of the Bean, and the attribute values ​​​​can be singleton (single case), prototype (prototype), request, session and global Session. The default value is singleton. The init-method  container calls this method when loading a Bean, similar to the init() method in Servlet.  The set method  is used to encapsulate Set type property injection. map  is used to encapsulate attribute injection of Map type. list Used to encapsulate property injection of List or array types.

Spring IOC (Inversion of Control)

Introduction

IoC is the abbreviation of Inversion of Control, translated as "Inversion of Control". It is not a technology, but a design idea. It is an important object-oriented programming rule that can guide us how to design loose coupling and better program.

Spring manages the instantiation and initialization of all Java objects through the IoC container, and controls the dependencies between objects. We call the Java objects managed by the IoC container Spring Beans, and there is no difference between them and the Java objects created using the keyword new.

The IoC container is one of the most important core components in the Spring framework. It runs through the entire process of Spring from its birth to its growth.

Inversion of Control (IoC)

1. In traditional Java development, if the service layer wants to call the properties or methods of the dao layer, it can only be achieved through a new object. But now Spring has proposed a new solution for us.

2. We only need to configure the java class in the configuration file or annotate the object through annotations. When Spring starts, the IoC container will be enabled to help us manage these objects. These objects created and managed by the IoC container are Called Spring Bean.

3. When we need to use these beans, we only need to use the getBean method of ApplicationContext to get the beans we need without new.

Here is a simple case

Case

Define the BookDao and BookService interfaces and implementation classes. The following is the specific content of the implementation classes.

package com.example.demo.dao.impl;

import com.example.demo.dao.BookDao;

public class BookDaoImpl implements BookDao {
    @Override
    public void save() {
        System.out.println("BookDaoImpl");
    }
}

复制代码
package com.example.demo.service.impl;

import com.example.demo.dao.BookDao;
import com.example.demo.dao.impl.BookDaoImpl;
import com.example.demo.service.BookService;

public class BookServiceImpl implements BookService {
    private BookDao bookDao;

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public void save() {
        this.bookDao.save();
    }
}

复制代码

xml configuration 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/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <bean id="bookDao" class="com.example.demo.dao.impl.BookDaoImpl"/>

        <bean id="bookService" class="com.example.demo.service.impl.BookServiceImpl">
                <property name="bookDao" ref="bookDao"/>
        </bean>
</beans>

复制代码

Application startup class

package com.example.demo;

import com.example.demo.dao.BookDao;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao =(BookDao) app.getBean("bookDao");
        bookDao.save();
    }
}
复制代码

Right-click to run the Application method to output the content in BookDao 

Dependency Injection (DI)

Dependency Injection (DI) In object-oriented, there is a relationship called "dependency" between objects. Simply put, a dependency relationship means that one object needs to use another object, that is, there is an attribute in the object, and the attribute is an object of another class. During the object creation process, Spring will automatically inject the objects it depends on into the current object based on the dependency relationships. This is the so-called "dependency injection". Dependency injection is essentially a type of Spring Bean property injection, except that this property is an object property. In the above case we configured the following

   <bean id="bookDao" class="com.example.demo.dao.impl.BookDaoImpl"/>
   <bean id="bookService" class="com.example.demo.service.impl.BookServiceImpl">
                <property name="bookDao" ref="bookDao"/>
   </bean>
复制代码

We use the property element to complete dependency injection. Instead of using constructor injection, we use elements in xml to inject bookDao. The name attribute is used to specify the name of the attribute that needs to be injected, and the ref attribute is used to specify the object that needs to be injected. In this way, we have completed the dependency injection operation.

Two implementations of IoC containers

ApplicationContext

ApplicationContext is a sub-interface of the BeanFactory interface and an extension of BeanFactory. We used this method in the above case.

  ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
复制代码

BeanFactory

BeanFactory uses a lazy-load mechanism. The container does not create a Java object immediately when loading the configuration file. It will only be created when the object is obtained (used) in the program.

BeanFactory app = new ClassPathXmlApplicationContext("applicationContext.xml");
复制代码

Spring Bean property injection

constructor injection

Suppose there is a Java class named Person, which has two properties: name and age, and a constructor that accepts the values ​​​​of these two properties.

package com.example.demo;

public class Person {
    public String name;
    public int age;
    public Person(){               //无参构造器

    }
    public Person(String name, int age) {          //提供有参构造器
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
复制代码

Now we want to use this Person class in a Spring application while injecting property values ​​using constructor injection. We can add the following bean configuration in the Spring configuration file:

<bean id="person" class="com.example.demo.Person">
                <constructor-arg value="张三" />
                <constructor-arg value="20" />
</bean>
复制代码

The above configuration defines a bean named person, whose type is Person. In the constructor-arg element, we specify that the constructor of the Person class needs to accept two parameters, namely "Zhang San" and 30, which are used to initialize the name and age attributes of the Person object.

When we need to use the Person object in our application, we can inject it like this:

package com.example.demo.service;

import com.example.demo.Person;

public class PersonService {
    private Person person;

    public PersonService(Person person) {
        this.person = person;
    }

}
复制代码

Test whether the injection is successful in Application

package com.example.demo;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
//        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        BeanFactory app = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = (Person) app.getBean("person");
        System.out.println(person.name);
        System.out.println(person.age);
    }
}
复制代码

Console output: Zhang San 30

setter injection

For setter injection, we can implement the person class file by modifying the above case without making any modifications. The configuration modifications in the Spring configuration file are as follows

<bean id="person" class="com.example.Person">
    <property name="name" value="张三" />
    <property name="age" value="20" />
</bean>
复制代码

In the above configuration, we use the property element to set the value of the name and age properties of the Person object.

Finally, in the class that needs to use the Person object, we can use setter injection to inject the person attribute into it:

package com.example.demo.service;

import com.example.demo.Person;

public class PersonService {
    private Person person;

    public void setPerson(Person person) {
        this.person = person;
    }
}
复制代码

The code in the Application file does not need to be changed. Right-click and run the output result: Zhang San 20

Spring automatic assembly

	//bookDao的定义
   <bean id="bookDao" class="com.example.demo.dao.impl.BookDaoImpl"/>
   //bookService的定义
   <bean id="bookService" class="com.example.demo.service.impl.BookServiceImpl">
   				//把bookDao和bookService联系在一起
                <property name="bookDao" ref="bookDao"/>
   </bean>
复制代码

In the implementation class of bookService, we only need to provide the setter method


    private BookDao bookDao;

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
复制代码

In the above code, we define a property named bookDao and provide a setter method named setBookDao. This setter method will be automatically called by Spring to inject the bookDao bean into the bookService bean.

Annotation development

Spring 3.0 enables pure annotation development and uses java classes instead of configuration files.

Configuration

package com.example.demo;

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

@Configuration              //申明该类为一个配置类
@ComponentScan("com.example.demo")              //扫描bean设置扫描路径
public class SpringConfig {

}
复制代码

This code replaces the configuration in xml and needs to be modified to the following when loading the configuration container and initializing it.

ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
复制代码

define beans

@Component		//它表示一个通用的 Spring 组件,可以用在任何层次上(如 DAO、Service、Controller 等)
@Service		// 通常用来注解业务层(Service 层)的组件,用于标识一个 Bean 是服务层组件。
@Controller		//通常用来注解控制层(Controller 层)的组件,用于标识一个 Bean 是 Web 控制器组件
@Repository		//通常用来注解数据访问层(DAO 层)的组件,用于标识一个 Bean 是数据访问组件
@Autowired 		//自动装配
复制代码

The above are the most basic and commonly used beans. With the above foundation, we can complete the following cases and create a new SpringConfig.class configuration class.

package com.example.demo;

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

@Configuration              //申明该类为一个配置类
@ComponentScan("com.example.demo")              //扫描bean
public class SpringConfig {

}
复制代码

Create a new UserDao class, declare it as a spring bean using @Repository, and set its name in parentheses.

package com.example.demo.dao.impl;

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDao {
    public void getUser(){
        System.out.println("getUser方法");
    }
}
复制代码

When declaring a UserService class, declare it to be a service layer bean, and also use Autowired to automatically assemble it.

package com.example.demo.service;

import com.example.demo.dao.impl.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    public UserDao userDao;
    @Autowired
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }
}
复制代码

Finally test in Application

package com.example.demo;

import com.example.demo.dao.impl.UserDao;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserDao userDao = (UserDao) app.getBean("userDao");
        userDao.getUser();
    }
}
复制代码

Console output: getUser method

Guess you like

Origin blog.csdn.net/2301_76607156/article/details/130557787