Reputation: 61
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.
Upvotes: 6
Views: 15827
Reputation: 62864
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.
Enable aspects in Spring by adding a <aop:aspectj-autoproxy/>
in your Spring configuration file.
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:
Upvotes: 7
Reputation: 6045
As kocko mentioned you could use aspects.
Beside that: I'm not sure if I understood you correctly, but do you really need to call initElements with each method-call? Or just when you create your page. In later case I would suggest to create an abstract page where you call your initElements-method and inherit every other page from it.
Upvotes: 0