Spring IOC/AOP use and source code explanation

Spring-IOC

Hi! This is the welcome page that you will display for the first time using the Markdown editor. If you want to learn how to use the Markdown editor, you can read this article carefully to understand the basic syntax of Markdown.

Use of IOC s

Basic use of IOC

  1. Import spring's pom configuration
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
    </dependencies>
  1. Create your own Bean
public class MyBean {
    private String name;
    public String getName() {return name;}
    public void setName(String name) { this.name = name;}
}
  1. Declare beans in spring's 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="myBean" class="ioc.beans.MyBean">
        <property name="name" value="123"></property>
    </bean>
</beans>
  1. Test Get Bean
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        MyBean myBean = (MyBean)context.getBean("myBean");
        System.out.println(myBean.toString());
    }
}

Bean injection method

  • get by id
    • Get object by unique id of bean
    • If the bean is not found, an error will be reported
  • get by type
    • Get Bean by Type of Class
    • If there are multiple of the same type, you need to specify the id, otherwise an error will be reported

Bean assembly method

Bean scope

There are four ways in spring 4.x, but only two in 5.x.
1. singleton: singleton is also the default scope of spring. There is only one instance in the entire container, which is created when the container is spawned.
2. prototype: multiple instances, an instance will be recreated each time it is used, and it will only be generated when it is used.
3. request(4.x): request scope.
4. session(4.x): Session scope.

BeanFactory and FactoryBean

Introduction to BeanFactory

BeanFactory is the basic class of Spring, which defines the operation of a single Bean. There is no specific implementation, and subclasses are required to implement it.

Introduction to FactoryBean

  1. Factory Bean is an interface provided by spring for creating complex beans. After inheriting this interface, the creation process of beans can be customized.
  2. The famous Mybatis uses FactoryBean to create connection objects (more on that later)

Use of FactoryBean

  1. Create MyFactoryBean to implement FactoryBean and override the method
public class MyFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return null;
    }
    @Override
    public Class<?> getObjectType() {
        return null;
    }
    @Override
    public boolean isSingleton() {
        return false;
    }
}
  1. The process of defining the Bean that needs to be created in MyFactoryBean
public class MyFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new MyBean();	//Define the process of creating a Bean and return the final generated Bean
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;	//Returns the type of the final generated Bean
    }

    @Override
    public boolean isSingleton() {
        return true;	//Define whether it is a singleton, true is a singleton, false is not a singleton
    }
}
  1. Declare MyFactoryBean in spring configuration file
<bean id="myFactoryBean" class="ioc.beans.MyFactoryBean" />
  1. Test to create MyBean using MyFactoryBean
public class MyTest {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        MyBean myBean = (MyBean)context.getBean("myFactoryBean");
        myBean.setName("123");
        System.out.println(myBean.toString());
    }
}

BeanPostProcessor

Introduction to BeanPostProcessor

BeanPostProcessor is an initialization pre/post processor provided by Spring to create beans. Many custom operations can be added in the process of Bean creation.
During the Spring startup process, there will also be an operation process for the BeanPostProcessor.

Use of BeanPostProcessor

  1. Define the Bean to implement BeanPostProcessor, and add the output before and after the Bean is created
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor Action before creation");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor Action after creation");
        return null;
    }
}
  1. Define the Bean in the configuration file
<bean id="myBeanPostProcessor" class="ioc.beans.MyBeanPostProcessor" />
  1. test and see the output
public class MyTest {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        MyBeanPostProcessor myBeanPostProcessor = (MyBeanPostProcessor)context.getBean("myBeanPostProcessor");
        System.out.println(myBeanPostProcessor.toString());
    }
}
  1. result
MyBeanPostProcessor Action before creation
MyBeanPostProcessor Action after creation
MyBeanPostProcessor Action before creation
MyBeanPostProcessor Action after creation
ioc.beans.MyBeanPostProcessor@617faa95

Bean's automatic assembly method

  1. default: no assembly
  2. byName: Assemble by name, assemble by set method
  3. byType: Assemble by type, assemble by set method
  4. Constructor: The same as assembling by type, except that it is assembled through the constructor instead of the set method

Annotation injection into Bean

You need to open the package scan in the configuration file, and then add the following annotations to inject into the IOC container.
Annotation type:

  1. @Component: Spring component, can be used anywhere
  2. @Controller: control layer
  3. @Service: business layer
  4. @Repository: Data Layer

Note: The above four annotations need to be injected into the IOC container for spring, and there is no difference. The so-called difference is only an artificial logical difference.

Difference between @Autoware and @Resource

@Autoware

  1. It is an annotation provided by spring. If spring is not used, the annotation will not take effect. (For example, this annotation cannot be used in mybatis)
  2. The default is to match by name (byName), if not by type (byType).

@Resource

  1. is an annotation provided by jdk.
  2. The default is to match by type (b'yType), if not by name (byName).

Tags: Java Spring

Posted by devxtech on Mon, 23 May 2022 21:49:15 +0300