Java Spring 在每次方法调用之前调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20519594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring invoke method before every method call
提问by user2904222
Is there any way to invoke a method before every method call for a bean?
有没有办法在每次调用 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.
我在春天使用硒和黄瓜。由于这个原因,所有页面都是单例,并且因为我使用 @FindBy 注释,所以每次使用页面时我都想调用 PageFactory.initElements(driver, object) 。
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.
我不想返回新页面,因为它们将无法在功能之间共享。
回答by Joachim Rohde
As kocko mentioned you could use aspects.
正如 kocko 提到的,您可以使用方面。
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.
除此之外:我不确定我是否正确理解你,但你真的需要在每次方法调用时调用 initElements 吗?或者就在您创建页面时。在后一种情况下,我建议创建一个抽象页面,您可以在其中调用 initElements-method 并从中继承所有其他页面。
回答by Konstantin Yovkov
Spring has a great AOP support and you can get benefits of it.
Spring 有很好的 AOP 支持,您可以从中受益。
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.
通过
<aop:aspectj-autoproxy/>
在 Spring 配置文件中添加 来启用 Spring 中的方面。创建一个简单的类并将其注册为一个方面。
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).
该MyFirstAspect
班。请注意,用@Aspect
注释标记。在该类中,您必须创建一个方法并将其注册为@Before
建议(建议在方法执行之前、之后或前后运行)。
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:
更多信息: