The container

  • In the midst of Java

If there is a class dedicated to holding objects of other classes, that class is called a container, or a collection. Containers are divided into sets, lists, and maps

  • On the Web, Tomcat is also a Web container

Tomcat is simple, to listen to an interface, to parse HTTP requests. However, how to initialize, how to parse the different protocols, and then call the resources, this step by step is called by the various design patterns, the various interfaces de-normalized… Tomcat manages your classes to make sure they are where they are supposed to be

An overview of the

  • The Inverse Of Control is a design idea that aims to guide the design Of loosely-coupled programs.

  • Control: In Java, control over objects (create, destroy).

  • Reversal: Refers to the reversal of object control from “developer manual control in the class” to “Spring container control.”

A rudimentary understanding of IOC

code

  • dao
public interface Car {
    void date(a);
}
class carA implements Car {
    @Override
    public void date(a) {
        System.out.println("carA....."); }}//carB, carC, similar
Copy the code
  • service
public interface CarService {
    void getCar(a);
}
public class CarServiceImpl implements CarService {
    Car car =new carA();
    @Override
    public void getCar(a) { car.date(); }}Copy the code
  • client
public class Client {
    public static void main(String[] args) {
        CarServiceImpl carService = newCarServiceImpl(); carService.getCar(); }}Copy the code

insights

  • When I need carB, I go to the service layer to delete carA, new A carB, and ask for C, the same is true when there are more clients, one needs A, one needs B, one needs C… It is troublesome to change.
  • You might say just new all the cars at once. First of all, the new keyword takes up resources. If there are 100 cars, would you write 100 new? You might say new is not tiring, but you have to write the corresponding method after new, and there are 100 of them, so it’s extremely troublesome.

To improve the

Only need to change in service and client:

public class CarServiceImpl implements CarService {
    private Car car;

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public void getCar(a) { car.date(); }}Copy the code

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

public class Client {
    public static void main(String[] args) {
        CarServiceImpl carService = new CarServiceImpl();
        carService.setCar(new carB());// What car do you wantcarService.getCar(); }}Copy the code

Controls the transfer of new Car permission from service to client

What does the big guy say