Spring invoke method before every method call

12,973

Spring has a great AOP support and you can get benefits of it.

What you have to do in order to solve your problem is.

  1. Enable aspects in Spring by adding a <aop:aspectj-autoproxy/> in your Spring configuration file.

  2. Create a simple class and register it as an Aspect.

Source:

<bean id="myAspect" class="some.package.MyFirstAspect">
   <!-- possible properties ... for instance, the driver. -->
</bean>

The MyFirstAspect class. Note that is marked with the @Aspect annotation. Within the class, you will have to create a method and register it as a @Before advice (an advice runs before, after or around a method execution).

package some.package;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MyFirstAspect {
    @Before("execution(* some.package.SomeClass.*(..))")
    public void initElements() {
        //your custom logic that has to be executed before the `clickThis`
    }
}

More info:

Share:
12,973

Related videos on Youtube

user2904222
Author by

user2904222

Updated on October 27, 2022

Comments

  • user2904222
    user2904222 over 1 year

    Is there any way to invoke a method before every method call for a bean?

    Im using selenium and cucumber with spring. All the pages are singletons because of this and since I'm using @FindBy annotations I want to invoke PageFactory.initElements(driver, object) every time a page is used.

    Using a standard page object pattern, this would be done by invoking it in the constructor.

    What I'd like to avoid is to specify in each method the method like so:

    public void clickThis() {
        PageFactory.initElements(driver, this)
        ...
    }
    
    public void clickThat() {
        PageFactory.initElements(driver, this)
        ...
    }
    

    I dont want to return the new page since they will not be able to be shared between features.

  • user2904222
    user2904222 over 10 years
    The state of the page might have changed since its first creation. For example, a menu has been toggled and to get updated WebElements in the java class I have to use initElements again.
  • user2904222
    user2904222 over 10 years
    Hmm, but I need to reference the actual instance of the class.
  • user2904222
    user2904222 over 10 years
    I'm thinking of skipping the @FindBy annotations and use driver.findElement(By selector) on each click instead. Feels like the most "readable" solution.
  • Konstantin Yovkov
    Konstantin Yovkov over 10 years
    No, you're not referencing an actual instance. The annotation does this for you
  • user2904222
    user2904222 over 10 years
    What I mean is that the code I want to run needs a reference to the instance. PageFactory.initElements(driver, this)
  • Konstantin Yovkov
    Konstantin Yovkov over 10 years
    Well...you can handle this by injecting a property in the aspect and instead passing this to pass the injected property.