Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring AOP to advise a bean of class X with certain id instead of all beans of class X

Tags:

java

spring

aop

In spring aop you can create advices that will effect all instance of a certain type but what I want is to advise a bean declaration not all beans of that type.

<bean id="bean1" class="type1"/>
<bean id="bean2" class="type1"/>

I want to advise bean1 not all beans of type1. What is the best approach?

like image 898
Yazan Jaber Avatar asked Aug 19 '11 05:08

Yazan Jaber


People also ask

How does Spring generate bean names for classes annotated with @component that do not specify a name?

How does Spring generate bean names for classes annotated with @Component that do not specify a name? It uses the short name of the class with the first letter in lowercase.

Can we create two beans with different id in Spring?

If you define two beans of same class, without different bean id or qualifiers ( identifier) , Spring container will not be able to understand which bean to be loaded , if you try to access the bean by passing the classname and you will get NoUniqueBeanDefinitionException as there are two qualifying TestBean.

What are the different advice types in Spring AOP?

AOP Advice TypesBefore Advice: These advices runs before the execution of join point methods. We can use @Before annotation to mark an advice type as Before advice. After (finally) Advice: An advice that gets executed after the join point method finishes executing, whether normally or by throwing an exception.

Can we use @before advice to prevent execution of a method?

In Spring AOP Before Advice is that executes before a join point i.e a method which annotated with AspectJ @Before annotation run exactly before the all methods matching with pointcut expression. But Before Advice does not have the ability to prevent execution flow proceeding to the join point.


1 Answers

From Spring Documentation regarding AOP:

Spring AOP also supports an additional PCD (PointCut Designator) named 'bean'. This PCD allows you to limit the matching of join points to a particular named Spring bean, or to a set of named Spring beans (when using wildcards). The 'bean' PCD has the following form:

bean(idOrNameOfBean)

The 'idOrNameOfBean' token can be the name of any Spring bean: limited wildcard support using the '*' character is provided, so if you establish some naming conventions for your Spring beans you can quite easily write a 'bean' PCD expression to pick them out. As is the case with other pointcut designators, the 'bean' PCD can be &&'ed, ||'ed, and ! (negated) too.

like image 164
nicholas.hauschild Avatar answered Sep 19 '22 05:09

nicholas.hauschild