Spring Aop (6) - Introducing @DeclareParents

6 Introduction to @DeclareParents

The @DeclareParents annotation is also provided by Aspectj. When using Spring Aop based on Aspectj annotations, we can specify through @DeclareParents in the aspect that a class that satisfies the specified expression will automatically implement certain interfaces. This just implements the specified interface for the generated proxy class at runtime. If there is an interface, there will be an implementation, and the corresponding implementation class also needs to be declared when @DeclareParents declares the automatically implemented interface. Now suppose we have an interface called CommonParent, and its implementation class is called CommonParentImpl, and the code is as follows.

public interface CommonParent {

	public void doSomething();
	
}
public class CommonParentImpl implements CommonParent {

	public void doSomething() {
		System.out.println("-----------do something------------");
	}

}

Then we hope that all our Service implementation classes can automatically implement the CommonParent interface at runtime, that is, all Service implementation classes can be used as CommonParent at runtime. Then we can define such an aspect class and the corresponding Advice as follows.

@Component
@Aspect
public class DeclareParentsAspect {

	@DeclareParents(value="com.elim.spring.aop.service..*", defaultImpl=CommonParentImpl.class)
	private CommonParent commonParent;
	
	@Before("bean(userService) && this(commonParent)")
	public void beforeUserService(CommonParent commonParent) {
		commonParent.doSomething();
	}
	
}

As above, we first declare an attribute of CommonParent type in the aspect class, and then use the @DeclareParents annotation above to indicate that we need to declare CommonParent as the parent interface of some specified types, and then specify the required effect through the value attribute of @DeclareParents Class form with a syntax similar to Pointcut expressions. The implementation class that specifies the default CommonParent interface through the defaultImpl attribute is CommonParentImpl. Then we declare an Advice of type before, in which we directly use our bean as an object of type CommonParent.

The whole process is like this, very simple. However, the author has not yet found which scenarios this can be applied to in practical applications. Welcome to exchange.

Reference document 1, official document

(Note: This article is based on Spring 4.1.0, written on Sunday, January 22, 2017)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268595&siteId=291194637