I got a task from my Java-language teacher to increase counter (id) in Restful web-service, using spring AOP before advice. Can't find how to do it. We use the default restful application from spring.io. Here is my modified code:
Application:
package sut.ist012m.Ruygo.hello_goodbye;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class Application {
public static void main(String[] args) {
final ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
final Controller Controller = run.getBean(Controller.class);
}
}
Controller:
package sut.ist012m.Ruygo.hello_goodbye;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
private static final String hellotemplate = "Hello, %s!";
private static final String adrtemplate = "Welcome to %s";
public AtomicLong counter1 = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name,
@RequestParam(value="city", defaultValue="Moscow") String city) {
return new Greeting(counter1.incrementAndGet(),
String.format(hellotemplate, name),
String.format(adrtemplate, city));
}
}
Greeting:
package sut.ist012m.Ruygo.hello_goodbye;
public class Greeting {
private final long id;
private final String content;
private final String adrcontent;
public Greeting( long id,
String content,
String adrcontent) {
this.id = id;
this.content = content;
this.adrcontent = adrcontent;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
public String getAdrcontent() {
return adrcontent;
}
CounterAspect(written by me):
package sut.ist012m.Ruygo.hello_goodbye;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class CounterAspect {
long id;
@Before(value="execution(* sut.ist012m.Ruygo.hello_goodbye.Greeting.*(..)) ")
public void beforeAdvice(JoinPoint joinPoint){
}
}
In normal way then you refresh web-page you see id=1,id=2,id=3... We want to see id=1,11,21,23 and so on. I can't understand what to write in "public void beforeAdvice". And is it OK that Spring doesn't control the "Greeting" class?