Dependency injection and AOP programming in Spring developed by JavaEE, javaeeaop

Source: Internet
Author: User

Dependency injection and AOP programming in Spring developed by JavaEE, javaeeaop

In the previous blog, we talked about how to build an Eclipse-based environment for Java EE development and how to create a Maven Web App. In the previous blog, we talked about dependency injection, in addition, Objective-C Runtime is used to implement dependency injection in ObjC. For related blogs, refer to "Implementing dependency injection in OC through Spring framework analogy". Of course, the previous blog also used the Runtime of ObjC to implement the "Aspect-Oriented" programming method in ObjC, for related blogs, go to AOP in ObjC-Aspect-Oriented Programming. In this blog, let's take a look at the dependency injection and AOP programming methods in the Spring framework. Of course, the implementation method is to use the "reflection mechanism" of Java, which is similar to the Runtime in ObjC.

The Spring version used in today's blog is 4.3.6.RELEASE, which is a relatively new Spring version. Java uses Java 8. In the previous blog, we primarily talked about environment Creation and configuration. This blog will not detail environment configuration. This blog mainly talks about the implementation of dependency injection in the Spring framework, mainly through annotations and Java configuration. Of course, we will also talk about some AOP.

 

1. quickly create a Spring project managed by Mava

Because this blog is about Spring, we will not create a WebApp project. We use Spring to quickly create a Maven-managed project. Find the File-> New-> Maven Project option to create a New Maven Project, as shown below:

  

 

Below we choose to create a simple Maven project, skip the Template Selection. In the previous blog, we did not select the option below when creating a Maven project. Then we chose a WebApp template. In this blog, we don't need a WebApp template. We only need a simple Maven project.

  

 

Enter the Organization Name and project name, as shown below. Click Finish to create a simple Maven project.

  

 

The following is the directory structure of the Maven project we have created. Our project code should be placed in src/main/java and will be used later.

  

After creating the above project, we will introduce our Spring dependency package in pom. xml. The xml below is the content in pom. xml. We first introduced the spring-context package, as shown below:

<Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> com. zeluli </groupId> <artifactId> SpringDemoWithMaven </artifactId> <version> 0.0.1-SNAPSHOT </version> <properties> <java. version> 1.8 </java. version> <sprin G. version> 4.3.6.RELEASE </spring. version> </properties> <dependencies> <! -- Introduction of Spring core package --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-context </artifactId> <version >$ {spring. version }</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId> org. apache. maven. plugins </groupId> <artifactId> maven-complier-plugin </artifactId> <version> 3.3.9 </version> <configuration> <source >$ {java. version} </source> <target >$ {java. version }</target> </configuration> </plugin> </plugins> </build> </project>

 

 

Ii. Dependency injection in Spring

Next, let's take a look at the call method of dependency injection in Spring. This part mainly talks about the two dependency injection methods in Spring. One is the annotation method, which is also commonly used, and the other is the Java configuration class method. Of course, xml is used for dependency injection in early Spring versions. Because of the complicated xml configuration and inconvenient management features, annotations and Java configuration are generally used in the project. The annotations and Java configurations are provided below, and their application scenarios are given.

 

1. Use annotations for dependency Injection

In this section, we will use annotations to declare beans in Spring. Mainly used@ ServiceAnnotation to declare the Bean used by the business logic layer (Service layer), use@ RepositoryAnnotation declares the Bean used by the data access layer (DAO layer), and uses@ ControllerAnnotation to declare the Bean of the presentation layer, use@ ComponentAnnotation component Bean. Of course, the underlying implementation of these annotations is similar, and their functions are similar, but their names are different.

We can use@ AutowiredTo declare the injection point of dependency injection, you can also use the @ Inject provided by the JSR-330 or@ ResourceAnnotation declaration injection point. The following describes how to use these annotations.

 

(1) @ Repository

The following code snippet is used@ RepositoryThe Bean declared by annotation will be used in the data access layer to declare the Bean of the DAO layer. We will use the RepositoryBean below later.

  

 

(2) @ Service

Below is what we use@ ServiceIn the business logic layer, we will use@ ServiceAnnotation for Bean declaration. In the code snippet below, after we declare ServiceBean using @ Service, we inject the RepositoryBean object into this class. Of course@ AutowiredThe injection point of the dependent object to be annotated. That is to say, at runtime, a dynamic allocationRepositoryBean. As follows:

  

 

(3) @ Component

@ ComponentIt is used to declare a Component. That is to say, You encapsulate a Component. This Component uses @ Component for annotation so that it can be injected. The following is the Component that uses the @ Component annotation declaration. We will call it in Controller later.

  

 

(4) @ Controller

Next we will use@ ControllerTo declare our controller.ControllerBeanIs our Controller class, of course, here we use @ Controller for annotation. Then in the Controller class, we use@ AutowiredAnnotation to inject ServiceBean and ComponentBean objects, and then use them in the corresponding method below.

  

 

(5) create a Spring configuration file

Next, we will create a Spring configuration file, because Spring can read some context information through this configuration file. Of course, the Spring configuration file is actually a Java class, And then we use@ Configuration. While@ ComponentScan ("package name ")Specifies the package of the component. That is, after this item is set, Spring automatically scans@ Component, @ Service, @ Repository, @ ControllerThese annotations.

  

 

(6) Create the Main function for testing.

The beans in the above columns have been created. Next, we will create the Main function for testing. First, we use annotations to configure the context.AnnotationConfigApplicationContextObject To obtain the Spring context from the Java configuration file. Then obtain the Controller Bean. The following shows the method for calling the Controller Bean. Close the called resource.

  

 

(7) running results

After the above implementation of the Main method, we can run it and see the running effect. The specific running result is as follows:

  

 

 

2. Java Configuration

The above section uses the annotations provided in Spring to declare various types of beans. Next, we will declare the related Bean in the Spring configuration file. Of course, the Bean declared in the Java configuration file is generally global, that is to say, if some beans need to be defined as global objects, we will declare the Bean in the Java configuration. For example, some common component beans can be put into the Java configuration file. Next, let's take a look at how Bean is declared in the Spring configuration file.

 

(1) create a Java configuration class

First, create a class. Here we name itJavaConfigBean. Then we need to declare it as Bean in the Spring configuration file. We can see that the following class is a common Java class, which does not use any annotations for modification.

  

 

(2) Declare Bean in the Spring configuration file

Next, we will use the @ Bean annotation in the Spring configuration fileJavaConfigBeanDeclared as a Bean object. The following code snippet is the content in the Spring configuration file. The createJavaConfigBean () method is used to generate the objects of the above classes. The @ Bean annotation is used to declare this method. This method returns the Java configbean class object. When Java configbean is used, the objects generated below are injected to the corresponding point.

  

 

(3) create a Controller dependent on JavaConfigBean

Next, we will create a Controller class. In this class, we will use the JavaConfigBean object. Below is the specific content of the ControllerBean class we created. The @ Autowired annotation is used to declare the injection points, as shown below:

  

 

(4) Create the Main function and test results

Next we should create a Main function for testing. The ControllerBean method is still called in the Main function, as shown below:

  

 

 

 

Iii. Aspect-Oriented Programming -- (Aspect Oriented Programming)

We have used the ObjCRuntimeTo demonstrate the implementation principle of AOP programming. Java's"Reflection mechanism. In fact, at runtime, we can implement AOP programming through the exchange of method bodies. The AOP programming in Spring is no exception. It is also implemented through method exchange. In this blog, let's take a look at how to use AOP programming in the Spring framework. This section provides two call schemes for AOP programming in the Spring framework. One is the annotation-based interception method, and the other is the method-based interception.

The following two methods of AOP programming are provided respectively. In the annotation-based interception method, we need to add annotations for the cut-point method, while the method-based interception does not need to do any operation on the cut-point method.

 

1. Introduce Spring's AOP dependency packages and AspectJ dependency packages

The XML content below is the relevant dependency configuration we want to add in pom. xml, and the spring-aop and aspectj dependencies are added below. Aspectj is also a Java dependency package for Aspect-Oriented Programming. What we need to do is also dependent on aspectj. The specific dependency package is introduced as follows:

<! -- Spring aop support --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-aop </artifactId> <version> 4.3.6.RELEASE </version> </dependency> <! -- Aspectj support --> <dependency> <groupId> org. aspectj </groupId> <artifactId> aspectjrt </artifactId> <version> 1.8.9 </version> </dependency>

 

 

2. annotation-based AOP

Next we will implement the annotation-based AOP implementation. Below we will create the annotation, face-cutting class, the Controller to be cut, the Spring configuration file, and the Main function for testing. The following describes the implementation of annotation-based AOP.

(1) Create the annotation used by AOP

First, create an annotation that will be used in the entry point. Select the corresponding package, and thenRight-click-> New-> AnnotationCreate an annotation.

  

The content in this annotation is relatively simple. The specific content is as follows:

package com.zeluli.aop.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Action {}

 

(2) create a cut-in Controller

Next we will create a cut-in Controller. Here we name this class AnnotationController. In the corresponding method of the Controller, we use the @ Action annotation we created above to declare it as the starting point of our aspect. The details are as follows:

  

 

(3) Compile the partition class

After defining the annotation @ Action for declaring the cut point and the Controller to be switched in, we should create the cut class. The LogAspect class created below is used to cut into the AnnotationController class. The specific content is as follows.

We use the @ Aspect annotation to declare the LogAspect class as a plane, and then use the @ Component annotation to declare it as a Component. The reason for declaring it as a component is that we can cut this section into many classes. Then we use the @ Pointcut annotation to specify the entry point. The @ Pointcut parameter is the annotation @ Action we created above. That is to say, the @ Action modifier method is our starting point. Use the @ Before annotation to declare the method to be executed Before the cut point, and use the @ After annotation to declare the method to be executed After the cut point. Below is the specific content of the LogAspect class.

  

 

(4) create a Spring configuration file

Next, we will create a configuration class. In the configuration class, we will enable AspectJ's automatic proxy, as shown below.

  

 

(5) Create the Main function for testing.

Next, we will start testing. The Main method is relatively simple, which is similar to the above Main method. The main purpose is to call AnnotationConfigApplicationContext to load the context from the configuration file, obtain the AnnotationController object according to the context, call the testMethod () method, and close the context.

public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext aopContext = new AnnotationConfigApplicationContext(AopConfig.class);        AnnotationController controller = aopContext.getBean(AnnotationController.class);        controller.testMethod();        aopContext.close();    }}

 

The following figure shows the running result of the preceding Main method. It can be seen that the @ Before method will be executed Before the testMethod () method is called. After the testMethod () method is executed, the @ After method will be executed. The specific results are as follows:

  

 

3. method-based AOP

We talked about the Aspect Based on Annotation interception. Next, let's take a look at the method-based aspect. That is to say, in this part, we will not create annotations. Directly create a LogAspect section. The LogAspect section below is a method-based section. The annotation @ Before or @ After is followed by a string, which is the class of the entry point. As shown below.

  

The Running Effect of the preceding section is the same as that of the annotation section, so we will not repeat it too much here.

 

This blog is here, the above Code on github share address: https://github.com/lizelu/SpringDemo

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.