Basic Application of Spring-IoC and AOP

Keywords: Java Spring xml Attribute

Preface

For any Java developer, Spring must be known like a thunderbolt. No one in the industry knows it. It's no exaggeration to say that Spring is the first framework in the Java field.


(Pictures from Spring's official website)

The concept of Spring was born in 2002. Rod Jahnson, the founder, first put forward the core idea of Spring in his book Expert One-on-One J2EE Design and Development, and officially released the first version of Spring Framework 0.9 in 2003.

After more than ten years of optimization iteration, Spring Framework has gradually evolved from the initial replacement of EJB framework to a complete ecosystem. The latest version is 5.X. It supports various technical fields of modern Java development. Spring Boot and Spring Cloud, two core members of the family, are the most popular technology stacks in the Java field. .

There is no doubt that Spring has become an industry standard for Java development. Whether you are a junior programmer or an architect, as long as you are doing Java development, you will be more or less exposed to Spring related technology stack in your work.

The Spring family bucket is derived from Spring Framework. The Spring Framework generally refers to Spring Framework. It includes many functional modules such as IoC control inversion, DI dependency injection, AOP aspect-oriented programming, Context context, bean management, Spring Web MVC, etc. All members of his Spring family depend on the Spring Framework.

It is easy to understand that Spring Framework is a design-level framework. Through layered thinking to achieve decoupling between components, developers can choose different components according to their needs and integrate them easily. This feature of Spring Framework makes enterprise-level project development more simple and convenient. .

The two core mechanisms of Spring are IoC (Control Inversion) and AOP (Aspect-Oriented Programming). For beginners, understanding these two core mechanisms is the basic application of Spring. These two core mechanisms are also typical representatives of Java design patterns, in which IoC is factory mode and AOP is proxy mode.

Click here to learn about Spring's Family Barrel

What is IoC and AOP

Let's get a detailed understanding of IoC. IoC is the soul of Spring Framework. It's very important to understand IoC in order to really grasp the use of Spring Framework.

IoC is also called control inversion. First of all, literally, what is control inversion? What is the reverse?

In traditional program development, it is usually the developer who creates instantiated objects manually when acquiring objects. However, the work of creating objects in Spring framework is no longer done by the developer, but is handed over to the IoC container to create them. We can get them directly, and the whole process completes the inversion, so it is the control inversion.

For example: Supermarket shopping.

  • Traditionally, when you go to the supermarket to buy something, you need to take the bag to the supermarket to buy the goods, and then bring the bag back by yourself.
  • IoC Container: You just need to put the bag in front of your house. The bag will automatically fill up the goods you need. Just take it out and use it.

We compare the differences between the two approaches by creating an example of a Student object.

Traditional way

(1) Create Student classes

public class Student {
    private int id;
    private String name;
    private int age;
}

(2) Calling constructors to create objects in test methods

Student student = new Student();

IoC container

Implementation steps
  • Add Spring dependencies to pom.xml
  • Create a configuration file to customize the file name spring.xml
  • Configure bean tags in spring.xml, and the IoC container creates objects by loading bean Tags
  • Call API to get the object created by IoC

IoC containers can call parametric constructs or parametric constructs to create objects. Let's first look at how parametric constructs work.

Parametric structure
<!-- To configure student object-->
<bean id="stu" class="com.southwind.entity.Student"</bean>

Configure a bean tag:

  • id, object name
  • Class, the template class of the object

Next, we call the API to get the object. Spring provides two ways to get the object: id or runtime class.

(1) Obtaining objects by id

//1. Load the spring.xml configuration file
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//2. Obtaining objects through id values
Student stu = (Student) applicationContext.getBean("stu");
System.out.println(stu);

Step 1: Load the spring.xml configuration file and generate the ApplicationContext object.

Step 2: Call the getBean method of ApplicationContext to get the object with the id value in the configuration file. When loading spring.xml, the program creates stu objects and calls parametric constructors through reflection mechanism. All classes required to be managed by IoC containers must have parametric constructors.

The results are shown in the following figure.

As you can see, the stu object's attributes are all empty at this time, because invoking a parametric construct only creates the object and does not assign it. How do you assign it? Just configure it in spring.xml, as shown below.

<!-- To configure student object -->
<bean id="stu" class="com.southwind.entity.Student">
    <property name="id" value="1"></property>
    <property name="name" value="Zhang San"></property>
    <property name="age" value="23"></property>
</bean>

Add the property tag: name corresponds to the attribute name, value is the value of the attribute. If it contains special characters, such as name="<Zhangsan>", use <![CDATA [<Zhangsan>]> to configure it, as shown below.

<!-- To configure student object -->
<bean id="stu" class="com.southwind.entity.Student">
   <property name="id" value="1"></property>
   <property name="name">
       <value><![CDATA[<Zhang San>]]></value>
   </property>
   <property name="age" value="23"></property>
</bean>

The results are shown in the following figure.

Spring completes the assignment of attributes by calling the setter method of each attribute, so the entity class must have the setter method, otherwise the loading time is wrong, and the getter method can be omitted.

(2) Obtaining objects through runtime classes

//1. Load the spring.xml configuration file
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//2. Obtaining objects through runtime classes
Student stu = applicationContext.getBean(Student.class);
System.out.println(stu);

One drawback of this method is that when two Student beans are configured in spring.xml, the program throws an exception, because both beans are generated by the Student class, and the IoC container cannot return both beans, so it must specify a unique bean.

<bean id="stu" class="com.hzit.entity.Student">
   <property name="id" value="1"></property>
   <property name="name">
       <value><![CDATA[<Zhang San>]]></value>
   </property>
        <property name="age" value="23"></property>
</bean>
<bean id="stu2" class="com.hzit.entity.Student">
   <property name="id" value="1"></property>
   <property name="name" value="Li Si"></property>
   <property name="age" value="23"></property>
</bean>

The exception information is shown in the following figure.

Above is how the IoC container creates objects by parametric construction. At the same time, the IoC container can also call parametric construction to create objects.

Parametric structure

(1) Create parametric constructs in entity classes

public Student(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
}

(2) Configuration in spring.xml

<!-- Creating objects through parametric constructors -->
<bean id="stu3" class="com.hzit.entity.Student">
   <constructor-arg name="id" value="3"></constructor-arg>
   <constructor-arg name="name" value="Xiao Ming"></constructor-arg>
   <constructor-arg name="age" value="22"></constructor-arg>
</bean>

(3) At this time, the IoC container will load the corresponding parametric constructor according to the constructor-arg tag, create the object and complete the attribute assignment. The value of name needs to correspond to the parameter name of the parametric construction, and value is the corresponding value. In addition to using name to correspond to parameters, you can also correspond by subscript index, as shown below.

<!-- Creating objects through parametric constructors -->
<bean id="stu3" class="com.hzit.entity.Student">
   <constructor-arg index="0" value="3"></constructor-arg>
   <constructor-arg index="1" value="Xiao Ming"></constructor-arg>
   <constructor-arg index="2" value="22"></constructor-arg>
</bean>

Above is how the IoC container creates objects by parametric construction. There are also two ways to get objects: id and runtime classes.

If the IoC container manages multiple objects and has cascading relationships among them, how can it be implemented?

(1) Create Classes classes

public class Classes {
    private int id;
    private String name;
}

(2) Add Classes attributes to the Student class

public class Student {
    private int id;
    private String name;
    private int age;
    private Classes classes;
}

(3) Configure the classes object in spring.xml and assign it to the stu object

<!-- Establish classes object -->
<bean id="classes" class="com.hzit.entity.Classes">
   <property name="id" value="1"></property>
   <property name="name" value="Java class"></property>
</bean>
<!-- Establish stu object -->
<bean id="stu" class="com.hzit.entity.Student">
   <property name="id" value="1"></property>
   <property name="name">
       <value><![CDATA[<Zhang San>]]></value>
   </property>
   <property name="age" value="23"></property>
   <!-- take classes Object assignment stu object -->
   <property name="classes" ref="classes"></property>
</bean>

Get the Student object again, as shown in the following figure.

In spring.xml, other beans are assigned to the current bean object by ref attribute. This method is called Dependency Injection (DI), which is a very important mechanism of Spring. DI is a way to associate different objects. It is the concrete implementation of IoC. Usually DI and IoC are closely combined, so it is general. IoC includes DI.

If it is a collection property, how does it depend on injection?

(1) Add List < Student > attribute to Classes class.

public class Classes {
    private int id;
    private String name;
    private List<Student> students;
}

(2) Two student objects and one class object are configured in spring.xml, and two student objects are injected into the classes object.

<!-- To configure classes object -->
<bean id="classes" class="com.hzit.entity.Classes">
   <property name="id" value="1"></property>
   <property name="name" value="Java class"></property>
   <property name="students">
       <!-- injection student object -->
       <list>
           <ref bean="stu"/>
           <ref bean="stu2"/>
       </list>
   </property>
</bean>
<bean id="stu" class="com.hzit.entity.Student">
   <property name="id" value="1"></property>
   <property name="name">
        <value><![CDATA[<Zhang San>]]></value>
   </property>
   <property name="age" value="23"></property>
</bean>
<bean id="stu2" class="com.hzit.entity.Student">
   <property name="id" value="2"></property>
   <property name="name" value="Li Si"></property>
   <property name="age" value="23"></property>
</bean>

The results are shown in the following figure.

Collection attributes are injected through list tags and ref tags, and ref bean attributes point to bean objects that need to be injected.

summary

In this lecture, we explain the basic concept of Spring IoC and how to use it. IoC is the core of Spring, which is very important. When using Spring to develop a project, the control layer, business layer and DAO layer all use IoC to complete dependency injection.

Please click here to download the source code.

Spring Communication

We are This course Payment readers have created Wechat Exchange Groups to facilitate more targeted discussion of curriculum-related issues. Please add the micro-signal of the assistant at the end of lesson 1-4 and indicate "family bucket".

Any questions you have in the process of reading the article can be discussed with other small partners at any time, or you can ask the author questions directly (after the author sees it, take time to reply). Your sharing not only helps others, but also improves yourself.

Warm Tip: You need to buy before you can join the group oh, add a small assistant Wechat, you need to check the purchased graph to verify.~

Click here to learn about Spring's Family Barrel

Posted by rameshmrgn on Mon, 05 Aug 2019 03:15:38 -0700