Three major frameworks: spring framework + IoC inversion of control, DI dependency injection

Three frameworks: business layer framework Spring+IoC+DI

Previous articles: jsp and cookie , redirection and RESTFul architecture support

Next chapter: Persistence layer framework MyBatis


Getting to know the Spring framework

Getting started with MyBatis https://www.w3cschool.cn/mybatis/mybatis-dyr53b5w.html

1. What problem to solve

Business layer:, 主要处理业务逻辑need objects, used to be own new objects, management objects, you can put the objects in the list or map.

2. What is it?

It is a business layer framework with two main functions.
2.1 It is an ioc container. The ioc container provides a hashMap (provides a container to store objects)
IOC: Inversion of Control (Inversion of Control ) Inversion of Control
: The creation of objects Reverse to (to) Spring

DI: Dependency injection, when the Spring framework is responsible for creating Bean objects, it dynamically injects dependent objects into Bean components! !
The key to understanding DI is: "Who depends on whom, why needs to depend, who injects whom, and what is injected", let's analyze in depth:
●Who depends on whom: Of course the application depends on the IoC container;
●Why depends on : The application needs the IoC container to provide the external resources needed by the object;
● Who injects whom: Obviously the IoC container injects an object of the application and the object that the application depends on;
● What is injected: What is needed to inject an object External resources (including objects, resources, constant data).
The relationship between DI and IOC: DI cannot exist alone, DI needs to be completed on the basis of IOC.

The advantages of doing this: achieve a single responsibility and improve reusability. After decoupling, you can implement it as you wish. The method invoked by the reference of the interface never needs to be changed.


2.2 aop function, dynamic proxy (detailed explanation of static proxy https://www.cnblogs.com/whirly/p/10154887.html ) created by programmers or automatically generated source code by specific tools, that is, the interface is already compiled when compiling, Determined by proxy class, proxy class, etc.

3. How to use?

3.1 Use xml configuration method (more troublesome)
3.2 Create a springboot project with spring built-in (the amount of code is small, it is recommended to learn spring for beginners)

It is judged whether the user name exists in the business layer during registration.
When obtaining the price of a product, it is determined whether the user is a member, whether the product has participated in store activities, and whether the product has participated in mall activities.
Insert picture description here

Spring's ambition

As a web framework, springMVC is loved by enterprises. It manages the Controller itself to create its instance. As an excellent framework for the persistence layer, Mybatis also manages persistent objects by itself. It can be seen that each prince manages objects by himself, and it is really cumbersome to reuse their objects.
How to break the game? To give orders to others, the best solution is to choke their throats. The most important thing in the java world is undoubtedly the life cycle management of objects. So Spring uses this as an entry point to achieve its own rule. Announce that all objects are managed by me, springMVC you no longer manage objects, I will manage them, and you have to take them from me. Mybatis you no longer manage the object, I will manage it, you have to use it from me. Do you care about it? These two great generals who have been fighting for several years will listen to the words of a fledgling young boy? Of course they won't listen, and spring can't listen, but they all listen to the developers. There are four cores to develop a complete system: WEB layer support, business logic layer, persistence layer support, and transaction support. And this is their weakness, this is their fate, they can only complete part of the work, not a total solution. And spring did not obliterate them, but remained high-ranking officials, acknowledging their market position, and also gifted a business management. While suppressing and drawing in, the two of them can only bow their heads when they see that the situation is over. As a result, a revolution was quietly emerging, and a classic three-tier framework was born SSM (SpringMVC+Spring+Mybatis).
The story is legendary, and people who listen to it are very happy. But is spring really that simple? If you think this way, you are very wrong. For example: how does spring implement object management? How can different technologies work together easily? This is the decisive point for spring.
It took great pains to realize these springs and innovatively formed a new theoretical system, which can be described as unprecedented.其中最核心的是:IoC控制反转、DI依赖注入、SpringAOP面向切面编程、事务控制。

Frame composition

Spring official website: http://spring.io
Spring is an open source framework, created to solve the complexity of enterprise application development. The Spring framework is not only a technical cow, but its core idea is even better. It does not repeat the invention of the wheel, but "uses it", which combines the best technologies in the industry to form a powerful enterprise-level application framework .

Realize ioc with springboot

demand

Insert picture description here

1. Copy webdemo to the workspace, directly rename the folder to spring01ioc, modify the antifactid and name in pom.xml, eclipse -->maven -->existing maven projects

Insert picture description here

Import eclipse
Insert picture description here

Modify to antifactid and name in pom.xml
Insert picture description here



2. Create a controller under the main package and create a UserController

The @autowired spring framework will take an object from the ioc container and assign it to userService UserService userService
Insert picture description here

3. Create a business layer Service

interface UserService{register}
Insert picture description here

@Service is similar to the controller. The UserServicelmpl class object is created by spring. The object
is stored in the ioc container (hashMap) in the spring framework.
class UserServicelmpl implements UserService

Step 1: Create an interface

Insert picture description here

package com.tedu.webDemo.service;

public interface UserService {
    
    
	public int register(String username);
}
Step 2: Create an interface implementation class

Insert picture description here

package com.tedu.webDemo.service;

import org.springframework.stereotype.Service;

//接口的实现类
@Service //告诉spring框架为类创建一个对象
//对象放在spring框架的ioc容器(hashMap)中
public class UserServiceImp1 implements UserService{
    
    
//返回类型最好用包装类型integer
	@Override
	public int register(String username) {
    
    
		//控制层springmvc调用业务层
		//判断用户名是否存在
		//调用数据库层mybatis
		return 0;
	}
}

Create a control layer
Insert picture description here

Step 3: Create the control layer
package com.tedu.webDemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tedu.webDemo.service.UserService;
import com.tedu.webDemo.service.UserServiceImp1;

//创建控制层
@RestController
public class UserController {
    
    
	//以前
	//UserController依赖UserServiceImp1
	//UserController被UserServiceImp1控制
	UserServiceImp1 UserServiceImp1=new UserServiceImp1();
	
	
	//控制层调用业务层,对象是从ioc容器中取
	//对象的类型要写接口,不要写具体的实现类的类型
	//对象从spring框架中来
	//被框架控制
	//控制反转ioc inversion of controller
	@Autowired
	UserService userService;
	
	@RequestMapping("/reg")
	//在控制层,业务层方法的第一行加断点
	//main() Debug AS
	//console 是否显示tomcat started on port 8080
	//localhost:8080/register F6,F8
	public String register(String username) {
    
    
		int state=userService.register(username);
		return "state="+state;
		
	}
}

class UserServicelmpl2
previously created an object and wrote this to death UserServicelmpl userServicelmpl = new UserServicelmpl()
When creating an object, change the object to interface UserService userService = new UserServicelmpl2();

summary

This is the IoC of the spring framework, the inversion of control. Before we created a new category ourselves. new UserService(), now provided by the container.
In the Java category, everything is Object, and in Spring, everything is Bean. Bean is the core, foundation and root of Spring.
Many students think that the above method is not appreciative. It feels that it is not as convenient as our traditional method. New objects are not enough. Out of thin air, what IoC, what DI messy feeling. Is that so? Not only do you think so, the industry also sneered at it at the beginning, but with the introduction of Spring 3.0, as the annotation method became the mainstream programming method in the market, its power began to show, let us laymen begin to admire it! This includes me.
We must constantly adapt to the ioc method



Life cycle:

Check the control layer in step 3.
When was the object created and when was it recycled?
By default, the controller is created when the system is started, and the
@scope("singleton") singleton is recycled when the system is shut down . Only one object is created
@scope(" ")

http://localhost:8080/reg?username=a
debug tracking process
Insert picture description here

Singleton,prototype,session

scope: singleton singleton, the object obtained each time is the same
prototype: the object obtained each time is a new one

analysis

AccessCount should have only one
LogInfo is created every time a new
UserCart is created by a user

demand

Requirement: add 1 to a user on the website, put it in accessCount
user shopping cart: userCart
log: logInfo

achieve

The function of @component is similar to that of @service. After adding @component, the framework will create objects. @service means business layer objects are created, and @component means ordinary objects are created.

Create three classes AccessCount, LogInfo, UserCart in the com.tedu.webDemo.service package

AccessCount class

package com.tedu.webDemo.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//组件:由框架管理的类
@Component //@Component是组件
//@controller,@restControler,@service都是组件
//@controller,@restControler,是专门用来接收数据
//@service类是专门处理数据的,是业务层的类

@Scope("singleton")
//单例,服务器启动时创建,关闭时 被回收
public class AccessCount {
    
    

}

LogInfo

package com.tedu.webDemo.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//处理日志,记录每次访问的时间
@Component
@Scope("prototype")//每次通过@autowired拿对象,都会创建一个新的
public class LogInfo {
    
    

}

UserCart

package com.tedu.webDemo.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//购物车 (浏览器打开的时候创建)
@Component
@Scope("session")//第一次访问时创建
//关闭浏览器,对象被回收
public class UserCart {
    
    

}

Modification: UserController control layer

package com.tedu.webDemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tedu.webDemo.service.AccessCount;
import com.tedu.webDemo.service.LogInfo;
import com.tedu.webDemo.service.UserCart;
import com.tedu.webDemo.service.UserService;
import com.tedu.webDemo.service.UserServiceImp1;

//创建控制层
@RestController
@Scope("prototype")
public class UserController {
    
    
	//以前
	//UserController依赖UserServiceImp1
	//UserController被UserServiceImp1控制
	UserServiceImp1 UserServiceImp1=new UserServiceImp1();
	
	
	//控制层调用业务层,对象是从ioc容器中取
	//对象的类型要写接口,不要写具体的实现类的类型
	//对象从spring框架中来
	//被框架控制
	//控制反转ioc inversion of controller
	@Autowired
	UserService userService;
	
	//从是spring框架的ioc容器中取对象
	@Autowired
	AccessCount accessCount;
	
	@Autowired
	LogInfo logInfo;
	
	@Autowired
	UserCart userCart;
	
	//测试商品对象
	@RequestMapping("/test")
	public String test() {
    
    
		return accessCount.toString()+"<br>"
				+logInfo.toString()+"<br>"
				+userCart.toString();
		
	}
	
	@RequestMapping("/reg")
	//在控制层,业务层方法的第一行加断点
	//main() Debug AS
	//console 是否显示tomcat started on port 8080
	//localhost:8080/register F6,F8
	public String register(String username) {
    
    
		
		int state=userService.register(username);
		return "state="+state+this.toString();
	}
}

http://localhost:8080/test
Debug AS执行
Insert picture description here

The business layer has multiple implementation classes

Case: In life, if your girlfriends are twins and the two sisters are the same, you will come home and you will find that both your girlfriends and sisters are there. How should you distinguish this time?
The spring framework finds all objects in the ioc container to determine the type of this object, and if it is UserService, assign the value
@autowired
UserService userSerivce

interface UserService
class UserServicelmpl

@service
class UserServiceImpl2 implements UserService

Automatic assembly type

Create another UserServiceImpl2 class in the service package

package com.tedu.webDemo.service;

import org.springframework.stereotype.Service;

@Service//spring框架会自动为类创建对象
//对象放在ioc容器中
public class UserServiceImpl2 implements UserService {
    
    
       public int register(String username) {
    
    
    	   return 0;
	}
}

Create two business layer implementation classes, error will occur by default

http://localhost:8080/reg
Insert picture description here
defaults to find objects
based on type

package com.tedu.webDemo.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

//处理日志,记录每次访问的时间
@Component
@Scope("prototype")//每次通过@autowired拿对象,都会创建一个新的
//用完就回收
public class LogInfo {
    
    
}

```java
package com.tedu.webDemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//接口的实现类
@Service //告诉spring框架为类创建一个对象
//对象放在spring框架的ioc容器(hashMap)中
//框架创建对象时,对象放在hashMap中,key是userServiceImpl
public class UserServiceImpl implements UserService{
//返回类型最好用包装类型integer
	@Override
	public int register(String username) {
		//控制层springmvc调用业务层
		//判断用户名是否存在
		//调用数据库层mybatis
		return 0;
	}
}
package com.tedu.webDemo.service;

import org.springframework.stereotype.Service;

@Service//spring框架会自动为类创建对象
//对象放在ioc容器中,key是userServiceImpl2
public class UserServiceImpl2 implements UserService {
    
    
	   @Override
       public int register(String username) {
    
    
    	   return 0;
	}
}
package com.tedu.webDemo.controller;

import javax.websocket.Decoder.TextStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tedu.webDemo.service.AccessCount;
import com.tedu.webDemo.service.LogInfo;
import com.tedu.webDemo.service.UserCart;
import com.tedu.webDemo.service.UserService;
import com.tedu.webDemo.service.UserServiceImpl;

//控制层
@RestController
@Scope("prototype")
public class UserController {
    
    
	
	
	//以前
	//UserController依赖UserServiceImpl
	//UserController被UserServiceImpl控制
	//UserServiceImpl UserServiceImpl=new UserServiceImpl();
	
	//控制层调用业务层,对象是从ioc容器中取
	//对象的类型要写接口,不要写具体的实现类的类型
	//对象从spring框架中来
	//被spring框架控制,依赖框架
	//控制反转 ioc inversion of controller
	@Autowired//默认是根据类型赋值
	//如果框架有2个对象的类型是UserService,赋值失败
	//先根据类型赋值,失败后,再根据对象的名称赋值
	//userServiceImpl,对象
	//userServiceImpl2,对象
	UserService userServiceImpl;
	
	@Autowired
	UserService userServiceImpl2;
	
	@Autowired
	@Qualifier("userServiceImpl2")
	//框架hashmap.get(userServiceImpl2),能取到对象
	//对象赋值给userService
	//先根据类型找到2个对象,赋值失败
	UserService userService;
	@RequestMapping("/test2")
	public String test2() {
    
    
		return userServiceImpl.toString()+"<br>"
				+userServiceImpl2.toString()+"<br>"
				+userService.toString();
	}
	
	//从spring框架的ioc容器中取对象
	@Autowired
	AccessCount accessCount;

	@Autowired
	LogInfo logInfo;
	
	@Autowired
	UserCart userCart;
	@RequestMapping("/test")
	public String test() {
    
    
		return accessCount.toString()+"<br>"
				+logInfo.toString()+"<br>"
				+userCart.toString();
	}
	
	@RequestMapping("/reg")
	//在控制层,业务层方法的第一行加断点
	//main() debug as 
	//console 是否显示 tomcat started on port 8080
	//localhost:8080/register  F6,F8
	public String register(String username) {
    
    
		int state=userServiceImpl.register(username);
		return "state="+state+this.toString();
	}
}
package com.tedu.webDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebDemoApplication {
    
    

	public static void main(String[] args) {
    
    
		SpringApplication.run(WebDemoApplication.class, args);
	}
}

Run as execution:
Insert picture description here

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112761533