Annotation Problems in Spring

Keywords: Java Spring JDK Attribute

Annotation Overview

Since JDK 5.0, Java has added support for metadata, namely Annotation.  
Annotation is actually a special tag in the code. It is used to replace the configuration file. That is to say, the traditional way tells the class how to run through the configuration file. With the annotation technology, developers can tell the class how to run through the annotation. A typical application of annotations in Java technology is that you can get annotations in classes through reflection technology to decide how to run classes.  

1. Customize a comment:

@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String temp() default "";
}

(1).@Retention - Defines the life cycle of the annotation
RetentionPolicy.SOURCE: Discarded during compilation. These annotations no longer make sense after compilation, so they don't write bytecodes. @ Override, @SuppressWarnings all fall into this category of annotations.
RetentionPolicy.CLASS: Discarded when classes are loaded. Useful in bytecode file processing. Annotations use this method by default
RetentionPolicy.RUNTIME: This annotation will never be discarded and will be retained during runtime, so you can use the reflection mechanism to read the information of the annotation. Our custom annotations usually use this approach.

(2).@Target - indicates where the annotation is used. The default value is any element, indicating where the annotation is used. The available ElementType parameters include
ElementType.CONSTRUCTOR: Used to describe constructors
ElementType.FIELD: Member variables, objects, attributes (including enum instances)
ElementType.LOCAL_VARIABLE: Used to describe local variables
ElementType.METHOD: Used to describe methods
ElementType.PACKAGE: Used to describe packages
ElementType.PARAMETER: Used to describe parameters
ElementType.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

2.Spring uses annotations.

In Spring Core Profile Configuration:

1 <context: component-scan base-package= "cn. *"/> <! -- Scan all beans under cn package-->
2 < context: component-scan base-package= "cn.pojo, cn.test"/> <! -- Scan the beans under the specified package, separated by commas - >"

If the scanned class has specific annotations (the following annotations), the object is handed over to the Spring container for management.

@ Component: This is a generic component form managed by Spring containers that can be placed on the class header and is not recommended.

1   @Component("userDao")//Here, an annotation defines a DAO
2   public class UserDaoImp implements IUserDao {
3      @Override
4     public int addUser(User user) {
5      //The database operation is not implemented here, just as an illustration.
6         System.out.println("Adding User Operations");
7           return 0;
8       }
9  }

@ Repository: Used to annotate DAO classes.

1 @Repository("userDao")
2 public class UserDaoImp implements IUserDao {
3     @Override
4     public int addUser(User user) {
5         System.out.println("Adding User Operations");
6         return 0;
7     }
8 }

This annotation is used in the data access layer to annotate the userdao class, and then the annotation is injected into the business logic layer.

1     @Resource(name="userDao")
2     
3     @Autowired
4     @Qualifier("userDao")
5     private IUserDao userDao;

Note provided by JDK: @Resource: Specify the corresponding dao class according to name and inject it into the userDao attribute.

Annotations provided within the Spring framework: @Autowired: Autoloads according to type, and injects according to name value with the @Qualifier annotation.

1. @Autowire can also inject the method into the input:

1     private IUserDao userDao;
2     
3     @Autowired
4     public void setUserDao(@Qualifier("userDao")IUserDao userDao) {
5         this.userDao = userDao;
6     }

2. Spring containers throw exceptions if a matching Bean component is not found when assembling with the @autowire annotation. If dependencies are not required, you can set the required property to false. The default is true, that is, you must find a matching Bean to complete the assembly, or you will throw an exception.

1     private IUserDao userDao;
2     
3     @Autowired(required = false)
4     public void setUserDao(@Qualifier("userDao")IUserDao userDao) {
5         this.userDao = userDao;
6     }

3. If the @autowire annotation is used for the member variables or methods of the collection type in the class, Spring injects all Bean components in the container that match the element types in the collection.

1      @Autowired(required = false)
2      private List<User> list;//Spring The container will User Type Bean Components are injected into list Attribute.

@ Service: Used to annotate business classes.

 1  @Service("userService")
 2  public class UserServiceImp implements IUserService {
 3      @Resource(name="userDao")
 4     private IUserDao userDao;
 5      
 6      @Override
 7     public int addUser(User user) {
 8          return userDao.addUser(user);
 9       }
10  }

@ The Service("userService") annotation tells Spring that when Spring wants to create an instance of UserService Impl, the name of the bean must be called "userService", so that when an Action needs to use an instance of UserService Impl,
You can create "userService" by Spring and inject it into Action: In Action, you only need to declare a variable named "userService" to receive "userService" injected by Spring.

@ Controller: Used to annotate the controller class, or Action.


Define aspects with annotations
AspectJ: An aspect-oriented framework that extends the Java language, defines AOP syntax, provides code weaving at compile time, and has a specialized compiler for generating standard Class files that comply with byte encoding.
@ AspectJ is a new function of AspectJ 5. It uses JDK 5.0 annotation technology and normal tangent expression language to describe aspects. Therefore, before using JDK, you need to ensure that the JDK version is more than 5.0, otherwise it can not be used.

1. Use annotations to mark sections

 1 package cn.advice;
 2 
 3 import org.apache.log4j.Logger;
 4 import org.aspectj.lang.JoinPoint;
 5 import org.aspectj.lang.ProceedingJoinPoint;
 6 import org.aspectj.lang.annotation.After;
 7 import org.aspectj.lang.annotation.AfterReturning;
 8 import org.aspectj.lang.annotation.AfterThrowing;
 9 import org.aspectj.lang.annotation.Around;
10 import org.aspectj.lang.annotation.Aspect;
11 import org.aspectj.lang.annotation.Before;
12 import org.aspectj.lang.annotation.Pointcut;
13 import org.springframework.stereotype.Component;
14 
15 @Component("serviceAdvice")
16 @Aspect
17 public class ServiceLoggingAdvice {
18     private Logger logger = Logger.getLogger(ServiceLoggingAdvice.class);
19     //Define entry points---Fuzzy queries can be used for matching
20     @Pointcut("execution(* cn.dao..*.*(..))")
21     public void pointcut(){}
22     //Annotation Pre-Enhancement
23     @Before(value = "pointcut()")
24     public void before(JoinPoint joinPoint){
25         String methodName = joinPoint.getSignature().getName();//Get the target method name
26         String className = joinPoint.getTarget().getClass().getSimpleName();//Get the class name of the target method
27         logger.info("Preamplifier....");
28         
29     }
30     //Post enhancement
31     @AfterReturning(pointcut="pointcut()")
32     public void after(JoinPoint joinPoint){
33         logger.info("Post enhancement....");
34     }
35     //Abnormal throw enhancement
36     @AfterThrowing(pointcut = "pointcut()",throwing = "e")
37     public void afterThrowing(JoinPoint joinPoint,Exception e){
38         String exeMessage = e.getMessage();
39         logger.info(exeMessage);
40     }
41     //Post enhancement
42     @After("pointcut()")
43     public void afterEnd(JoinPoint joinPoint){
44         logger.info("Final enhancement....");
45     }
46     //Surround enhancement
47     @Around("execution(* cn.service..*.*(..))")
48     public Object round(ProceedingJoinPoint joinPoint){
49         Object result = null;
50         try {
51             logger.info("Surround enhancement ------Front..");
52             
53             result = joinPoint.proceed();//This method calls the real target method to achieve complete control of the join point.
54             
55             logger.info("Surround enhancement ------Later.");
56         } catch (Throwable e) {
57             e.printStackTrace();
58         }
59         return result;
60     }
61 }

2. In the core XML configuration file

(1) First import the aop namespace

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xmlns:context="http://www.springframework.org/schema/context"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 9      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10      http://www.springframework.org/schema/tx
11      http://www.springframework.org/schema/tx/spring-tx.xsd
12      http://www.springframework.org/schema/aop 
13      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
14      http://www.springframework.org/schema/context
15      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
16 </beans>

(2) Adding < aop: aspectj-autoproxy /> elements to the core configuration file enables support for @AspectJ annotations, and Spring automatically creates proxies for matching beans.

Summary:

1. The annotated java class is treated as a Bean instance. The name of the Bean instance is lowercase by default, and the rest is unchanged. @ Service can also customize the Bean name, but it must be unique!

2. Replace @Component annotations with classes corresponding to component annotations as much as possible. In future versions of spring, @Controller, @Service, @Repository will carry more semantics. And easy to develop and maintain!

Posted by ghettopixel on Fri, 10 May 2019 06:50:00 -0700