Spring AOP:A passagem de parâmetros no aspecto método
Pergunta
Eu sou novo para Spring AOP e tentando criar uma demo usando aop:around
.
Um simples feijão classe:
public class Employee {
private String name;
public String getName() {
System.out.println("Name: " + name);
return name;
}
public void setName(String name) {
this.name = name;
}
}
Aspectos de implementação:
public class PrintingAspect {
public void performPrinting(ProceedingJoinPoint point){
try {
System.out.println("Before Printing!!!");
point.proceed();
System.out.println("After Printing!!!");
} catch (Throwable e) {
System.out.println("Exception Printing");
}
}
}
Contexto XML:
<bean id="aspect" class="com.aop.aspect.PrintingAspect">
</bean>
<bean id="employee" class="com.aop.model.Employee">
<property name="name" value="XXX"></property>
</bean>
<aop:config>
<aop:pointcut id="empName" expression="execution(* com.aop.model.Employee.getName(..))"/>
<aop:aspect ref="aspect">
<aop:around pointcut-ref="empName" method="performPrinting"/>
</aop:aspect>
</aop:config>
App.java
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Employee empl = (Employee)context.getBean("employee");
System.out.println("Employee Names: " + empl.getName());
}
}
O s/p, eu estou ficando é:
Antes De Imprimir!!!Nome:XXX Após A Impressão!!!Os Nomes De Funcionários:null
Por que é o último nulo ?
Solução
Uma maneira de fazer isso é com essas alterações:
XML:
<aop:pointcut id="empName"
expression="execution(* com.example.Employee.getName(..))" />
Java:
public void performPrinting(ProceedingJoinPoint jp) { // Here empl is coming null
System.out.println("Before Printing!!!");
System.out.println(((Employee)jp.getTarget()).getName()); // empl is coming as NULL
System.out.println("After Printing!!!");
}
Em outras palavras, você tem acesso para o target
qual é o objeto que está sendo intermediado por proxy para o AOP conselhos para ser aplicada.
Outras dicas
Point.proceed() no código abaixo é responsável pela execução real do código e como você está usando conselhos, você deve capturar o valor de retorno e retornar no método abaixo.Como você não retorna nada no método abaixo, ele vem como nulo.
Por favor, deixe-me saber se não funcionar. Não testei, mas funcionará.
public void performPrinting(ProceedingJoinPoint point){
try {
System.out.println("Before Printing!!!");
Object returnValue = point.proceed();
System.out.println("After Printing!!!");
} catch (Throwable e) {
System.out.println("Exception Printing");
}
return returnValue;
}