JAVA reflection and Spring framework

Directory

1. Overview of Spring

Spring framework was created due to the complexity of software development. Spring uses basic JavaBeans to do things that were previously only possible with EJBs. However, the use of Spring is not limited to server-side development. The vast majority of Java applications can benefit from Spring in terms of simplicity, testability, and loose coupling.

2. Spring’s management of beans

1. The way to create beans

1. Overview of reflection

The JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic information and dynamic call The function of the method of the object is called the reflection mechanism of the java language. To dissect a class, you must first obtain the bytecode file object of the class. The dissection uses the methods in the Class class. So first, get the Class type object corresponding to each bytecode file.

Two, Class class

Third, the use of reflection

1. Three ways to obtain Class objects

1.1 Object –> getClass(); 1.2 Any data type (including basic data types) has a “static” class attribute 1.3 Through the static method of the Class class: forName (String className) (commonly used)

Finally create a test class: Create a serclet package and create four test classes BookServlet, Test01, Test02, Test03

1. Spring Overview

The Spring framework was created due to the complexity of software development. Spring uses basic JavaBeans to do things that were previously only possible with EJBs. However, the use of Spring is not limited to server-side development. The vast majority of Java applications can benefit from Spring in terms of simplicity, testability, and loose coupling.

The role of spring: it mainly solves the problems of creating objects and managing objects.

The core of Spring:

IOC (Inversion of Control): inversion of control, that is, the problem of object creation
AOP (Aspect Oriented Programming): Aspect Oriented Programming

IOC and DI

IOC: Inversion of Control, which transfers the calling right of the object directly controlled by the program code to the container, and realizes the assembly and management of components through the container. The essence is the transfer of the calling right of the object, and the right to create the object delivered to the container
DI: Dependency Injection, during runtime, an external container dynamically injects a dependent object into another object

What IOC describes is an idea, and DI is the concrete realization of the idea of IOC

2. Spring’s management of beans

1. Ways to create beans

1. By default, the constructor is used to create

Use the bean tag in the Spring configuration file. After configuring the id and class attributes, when there are no other attributes and tags, the default constructor is used to create the bean object. At this time, if there is no default constructor in the class, the object cannot be created.

?

case:

First import the framework package required by spring:

http://Link: https://pan.baidu.com/s/1RsEcnBVAD50m86m5kdEKpw?pwd=1314 Extraction code: 1314

Create a spring.xml configuration file in src

Link: https://pan.baidu.com/s/1EuTHmIlHME6m-IJlyBp5Lw?pwd=1314
Extraction code: 1314

spring.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">
    <!--Tell the spring framework which objects to create and manage
    id: Give the created object a name
    class: The full class name of the class corresponding to the object to be created
    -->
  <bean id="bookDao" class="com.nai.dao.impl.BookDaoImpl"></bean>
    <bean id="bookService" class="com.nai.service.impl.BookServiceImpl">
        <!--Input data to the properties of the class through property: the default is to use the setter method
        Regular types use value injection
        Objects are referenced above using ref:
        -->
        <property name="name" value="Zhang San"/>
        <property name="age" value="22"/>
        <property name="bookDao" ref="bookDao"/>
    </bean>
</beans>

The overall structure of spring:

?

Corresponding code:

Create a BookDao interface and BookDaoImpl implementation class in com.nai.dao.impl

BooKDao interface:

package com.nai.dao;

public interface BookDao {
    public void insert();

}



BookDaoImpl class:

package com.nai.dao.impl;

import com.nai.dao.BookDao;
//implementation class
public class BookDaoImpl implements BookDao {
    @Override

    public void insert() {
        System.out.println("BookDaoImpl...save");

    }
}

Create BookServiceImpl implementation class, BookServiceVip implementation class, and BookService interface in com.nai.service.impl

BookService interface:

package com.nai.service;

public interface BookService {
void save();

}

BookServiceImpl implementation class:

package com.nai.service.impl;

import com.nai.dao.BookDao;
import com.nai.service.BookService;

public class BookServiceImpl implements BookService {

    public String name;
    public int age;
    private BookDao bookDao;

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

    public void setAge(int age) {
        this. age = age;
    }

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

    @Override
    public String toString() {
        return "BookServiceImpl{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", bookDao=" + bookDao +
                '}';
    }
    @Override
    public void save() {
        System.out.println("BookServiceImpl..save");
        bookDao. insert();
    }
}

BookServiceVip implementation class:

package com.nai.service.impl;

import com.nai.service.BookService;

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

Finally create the test test class

Test01 test class:

package com.nai.test;

import com.nai.service.BookService;
import com.nai.service.impl.BookServiceImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {
    BookService bookService;
    @Test
    public void test01(){
        //The creation of the object is created by the spring framework, here you only need to directly ask the IOC container
        //1. Load spring.xml through ClassPathXmlApplicationContext to get the IOC container
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
       //2. Obtain the object by name from the IOC container
        bookService= (BookService) context. getBean("bookService");
        bookService. save();

    }

}

?

1. Overview of reflection

JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can It can call any of its methods and properties; this dynamically obtained information and the function of dynamically calling the method of the object are called the reflection mechanism of the java language.
To dissect a class, you must first obtain the bytecode file object of the class. And the dissection uses the method in the Class class. So first get the Class type object corresponding to each bytecode file.

All in all, reflection is to map various components in the java class into individual Java objects

JAVA reflection is the soul of the framework!

Preconditions for use: You must first obtain the Class representing the bytecode, which is used to represent the .class file (bytecode)

Two, Class

Class class related to -String string processing

?

Instances of the Class class represent classes and interfaces in a running Java application. That is, there are more than N instances in the jvm, and each class has the Class object. (including primitive data types)
Class has no public constructor. Class objects are constructed automatically by the Java virtual machine when a class is loaded and by calling the defineClass method in the class loader. That is, we don’t need to handle the creation ourselves, the JVM has already created it for us.

?

Three, the use of reflection

Create a Book class

package com.nai.bean;

public class Book {
    //Attributes of the class---storage data
    public String name;
    int age;
    protected String sex;
    private String address;

    public Book() {
        
    }

    public Book(String name, int age, String sex, String address) {
        this.name = name;
        this. age = age;
        this. sex = sex;
        this.address = address;
    }

    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;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this. sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", sex='" + sex + ''' +
                ", address='" + address + ''' +
                '}';
    }
}

1. Three ways to get Class objects

?

Then create the dao package and add the interface BookDao and BookImpl class

BookDao interface:

package com.nai.dao;

public interface BookDao {

    public void add();

}

BookImpl class:

package com.nai.dao.Impl;

import com.nai.dao.BookDao;

public class BookDaoImpl implements BookDao {

        public void add(){

            System.out.println("BookDaoImpl..add");
        }
}

Also create a servise package, which creates two classes BookServiseImpl, BookServiseVip and BookServise interface

BookServiseImpl class:

package com.nai.servise.Impl;


import com.nai.dao.BookDao;
import com.nai.dao.Impl.BookDaoImpl;
import com.nai.servise.BookService;

public class BookServiceImpl implements BookService {
    BookDao bookDao=new BookDaoImpl();

    //Function method --- complete some programs or functions
    @Override
    public void add() {
        System.out.println("BookServiceImpl...add");
        bookDao. add();
    }

    public void fun(){
        System.out.println("BookServiceImpl...fun");
    }
}

BookServiseVip class:

package com.nai.servise.Impl;

import com.nai.dao.BookDao;


import com.nai.dao.Impl.BookDaoImpl;
import com.nai.servise.BookService;

public class BookServiceVip implements BookService {
    BookDao bookDao=new BookDaoImpl();
    @Override
    public void add() {
        System.out.println("BooKServiceVip...add");
        bookDao. add();
    }

    public void fun(){
        System.out.println("BookServiceImpl...fun");
    }
}

BookServise interface:

package com.nai.servise;

public interface BookService {

    
        public void add();

        public void fun();
    }

Call method:
1. Obtain the construction method
:
1). Batch method:
public Constructor[] getConstructors(): all “public” constructors
public Constructor[] getDeclaredConstructors(): Get all constructors (including private, protected, default, public)

2). Get a single method and call:
public Constructor getConstructor(Class… parameterTypes): Get a single “public” constructor:
public Constructor getDeclaredConstructor(Class… parameterTypes): Get “a certain constructor” can be private, or protected, default, public;

Call the constructor:
Constructor–>newInstance(Object… initargs)

2. newInstance is a method of the Constructor class (the class that manages the constructor)
The explanation of api is:
newInstance(Object… initargs)
Uses the constructor represented by this Constructor object to create a new instance of the constructor’s declaring class and initializes the instance with the specified initialization parameters.
Its return value is of type T, so newInstance creates a new instance object of the declared class with a constructor. and call for it.

Finally create test classes: Create four test classes BookServlet, Test01, Test02, Test03 in the serclet package

BookServlet test class:

package com.nai.servlet;


import com.nai.servise.BookService;
import com.nai.servise.Impl.BookServiceVip;
import org.junit.Test;

public class BookServlet {
    BookService bookService=new BookServiceVip();

    @Test
    public void add(){
        System.out.println("BookServlet...add");
        bookService. add();
    }
}

operation result:

?

Test01 test class:

package com.nai.servlet;



import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Application of reflection
 */
public class Test01 {
    public static void main(String[] args) throws Exception {
        //Load the Class object of the class through the full class name
        Class cla = Class.forName("com.nai.servise.Impl.BookServiceImpl");
        //Class object can be considered as the scalpel of the class, which can dissect the things in the class--properties, constructors, methods
        Field[] fields = cla.getFields(); //Only get public modified attributes
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("-------------");
        Field[] fields1 = cla.getDeclaredFields(); //Get all attributes
        for (Field field : fields1) {
            System.out.println(field);
        }

        System.out.println("========================");

        Constructor[] constructors = cla. getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("-------------");
        Constructor[] constructors1 = cla. getDeclaredConstructors();
        for (Constructor constructor : constructors1) {
            System.out.println(constructor);
        }

        System.out.println("========================");
        Method[] methods = cla. getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("-------------");
        Method[] methods1 = cla. getDeclaredMethods();
        for (Method method : methods1) {
            System.out.println(method);
        }
    }
}

operation result:

?

Test02 test class:

package com.nai.servlet;


import com.nai.servise.BookService;

import java.io.InputStream;
import java.lang.reflect.Constructor;

import java.util.Properties;

/**
 * Micro frame
 */
public class Test02 {
    public static void main(String[] args) throws Exception {
        //Read the configuration file and get the content
// File file=new File("D:\code\IdeaProjects\spring2105\spring01\src\info.properties");
// InputStream stream=new FileInputStream(file);
        InputStream stream = Test02.class.getClassLoader().getResourceAsStream("info.properties");

        Properties p = new Properties();
        p.load(stream);
        String className = p. getProperty("className");

        //1. Get the Class object of the class through the full class name
        Class cla = Class. forName(className);
        //2. Obtain the parameterless constructor of the class through the Class object
        Constructor constructor = cla. getDeclaredConstructor();
        //3. Use the constructor to create an object
        BookService bookService = (BookService) constructor. newInstance();
        //4. Use the object to call the method
        bookService. add();
    }
}

operation result:

?

Test03 test class:

package com.nai.servlet;

import com.nai.servise.BookService;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * Micro frame
 */
public class Test03 {
    public static void main(String[] args) throws Exception {
        //Read the configuration file and get the content
//
        InputStream stream = Test03.class.getClassLoader().getResourceAsStream("info.properties");

        Properties p = new Properties();
        p.load(stream);
        String className=p. getProperty("className");
        String methodName=p. getProperty("methodName");

        //1. Get the Class object of the class through the full class name
        Class cla = Class. forName(className);
        //2. Obtain the parameterless constructor of the class through the Class object
        Constructor constructor = cla. getDeclaredConstructor();
        //3. Use the constructor to create an object
        BookService bookService = (BookService) constructor. newInstance();
        //4. Get the method name
        Method method = cla. getDeclaredMethod(methodName);
        //5. Execution method
        method.invoke(bookService);
    }
}

operation result:

?