I am implementing a service
for my controller in java. This service implements an interface with several methods, where each of them performs a different logic. However, they also have a common logic (they must call another @service).
I would like to know if there is any way to refactor this, that is, remove that common logic that they have to a method in the class of my service that is executed only once, at the beginning.
I'm looking for something similar to the following:
public class myClass implements myInterface{
private String stringToFill="";
@Before
public doSomeLogig(){
// call another service
stringToFill = "filled";
}
public getAll(){
...
//here I should use stringToFill, with value 'filled'
}
public getId(){
//here I should use stringToFill, with value 'filled'
...
}
public create(){
//here I should use stringToFill, with value 'filled'
...
}
}
CodePudding user response:
There is a spring lifecycle annotation called as @PostConstruct, write a method in the class and add all the one time execution logic in this method and annotate it with the @PostConstruct annotation and spring would call this method automatically once the bean has been initialized.
CodePudding user response:
Using AOP you can call a method in lots of different scenarios including the one you described. Here is Link to Spring AOP documentation Spring AOP
@Aspect
public class BeforeExample {
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doAccessCheck() {
// ...
}
}
You can Also define a custom annotation like @Before to do the magic for you.