Spring AOP by annotation pointcut annotation not retrieve - spring-aop

I'm using Spring AOP for intercept annoted methods by #MyAnnotation. The intercepting is ok. but, unfortunately, i'm not arrive to have my annotation instance.
My Annotation :
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface MyAnnotation {
String[] description();
}
My Configuration Aspect
#Aspect
public class OAuthAspect {
#Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
}
#Pointcut(value = "#annotation(annotation)", argNames = "annotation")
public void anyAnnotationMethod(MyAnnotation annotation) {
}
#Around(value = "anyPublicMethod() && anyAnnotationMethod(annotation)")
public Object authorization(ProceedingJoinPoint pjp, MyAnnotation annotation) throws Throwable {
//annotation is null
}
}
Example pointcut :
#Service
public class ContextService {
#MyAnnotation(description = {"de1", "des2"})
public String getAll() {
}
}
I don't understand why I can't retrieve the instance of the annotation.
if someone have an idea?
pc : edited

For me the class ContextService does not even compile because of a typo in your annotation: String[] descrition(); (note the missing "p") should really be String[] description();, then it compiles and I can also print the annotation instance.

Related

Apache Camel Generic Router - pass exchange properties to static class methods

I am trying to create a generic router whose processor and other attributes are populated from a static class. Here is sample code.
public class GenericRouter extends RouteBuilder( {
#Override
public void configure() throws Exception {
from("direct:generic-route")
.process(Util.getProcesss(“${exchangeProperty[processKey]"))
.ToD(Util.getUrl(“${exchangeProperty[urlKey]"));
}
}
Public class Util{
Map<String,Object> routerResources;
static {
//load routerResources
}
public static Processor getProcessor(String processorKey){
return (Processor)routerResources.get(processorKey);
}
public static Processor getUrl(String urlKey){
return (String)routerResources.get(urlKey);
}
}
The generic router is expected to post a rest call. the properties "urlKey" and "processorUrl" are already available in exchange. I finding it difficult to pass exchange properties to static Util class methods.
If you want to access properties of an exchange in plain java you can use .process or .exchange. If you need to access body or headers you can use e.getMessage().getBody() and e.getMessage().getHeader()
from("direct:generic-route")
.process( e -> {
String processKey = e.getProperty("processKey", String.class);
Processor processor = Util.getProcessor(processKey);
processor.process(e);
})
.setProperty("targetURL").exchange( e -> {
String urlKey = e.getProperty("urlKey", String.class);
return Util.getUrl(urlKey);
})
.toD("${exchangeProperty.targetURL}");
Also make sure you fix the return type of this method:
public static Processor getUrl(String urlKey){
return (String)routerResources.get(urlKey);
}
As a side note, you can actually use map stored in body, header or property through simple language.
public class ExampleTest extends CamelTestSupport {
#Test
public void example(){
template.sendBodyAndHeader("direct:example", null, "urlKey", "urlA");
}
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
Map<String, String> urlMap = new HashMap<>();
urlMap.put("urlA", "direct:pointA");
urlMap.put("urlB", "direct:pointB");
from("direct:example")
.setProperty("urlMap").constant(urlMap)
.log("url: ${exchangeProperty.urlMap['${headers.urlKey}']}");
}
};
}
}

Hystrix to Resilience4J

I've been working with Hystrix but now I want to change one project from Hystrix to Resilience4J but I don't not how!
My code is as follow:
#FeignClient(name = "customer-service", fallback = CustomerHystrixFallbackFactory.class)
public interface CustomerClient {
#GetMapping(value = "/customers/{id}")
public ResponseEntity<Customer> getCustomer(#PathVariable("id") long id);
}
And my CustomerHystrixFallbackFactory as follow:
#Component
public class CustomerHystrixFallbackFactory implements CustomerClient{
#Override
public ResponseEntity<Customer> getCustomer(long id) {
Customer customer = Customer.builder()
.firstName("none")
.lastName("none")
.email("none")
.photoUrl("none").build();
return ResponseEntity.ok(customer);
}
}
The thing is when customer-service is down, it returns none, but not a 500 Error message.
So, how can I convert what I have to apply Resilience4J?
Thanks in advance!

React Js and Spring boot faster xml jackson databin

Hello when i try to get all values with this path : localhost:8080/aspsort/all
i get error :
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:166) ~[jackson-databind-2.10.3.jar:2.10.3]
the method is :
#GetMapping("/all")
public Iterable<Rfpobject> getallRFP()
{
return rfprepo.findAll();
}
instead of Iterable try changing it to List as return type .
and in rfprepo interface add this
#Override
List<Data> findAll();
example
#Autowired
RfpRepository rfprepo;
#GetMapping("/all")
public Iterable<Rfpobject> getallRFP()
{
return rfprepo.findAll();
}
public interface RfpRepository extends CrudRepository<Rfpobject, Long> {
#Override
List<Rfpobject> findAll();
}
let me know if this solved your issue.

Execute aspect advice in same transaction context

I am trying to use Spring-AOP/AspectJ on the methods in a class annotated with #Transactional. So, I have two model DAO classes like this:
#Transactional
#Repository
public class ModelDAO {
public void save() {
}
}
#Transactional
#Repository
public class AnotherModelDAO {
public void save() {
}
}
And then an Aspect like:
#Aspect
public class ModelAspect {
#Around("publicMethod() && isModelClassSaveCalled()")
public Object doAspect(ProceedingJoinPoint joinPoint) throws Throwable {
joinPoint.proceed();
anotherModelDAO.save();
}
}
So, my question is: Is it possible to call model.save() and anotherModel.save() to be called in same transaction context through aspect as mentioned above?
Any help will be much appreciated.

Intercepting annotated methods using Spring #Configuration and MethodInterceptor

I need to intercept annotated methods using spring-aop.
I already have the interceptor, it implements MethodInterceptor from AOP Alliance.
Here is the code:
#Configuration
public class MyConfiguration {
// ...
#Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
}
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface MyAnnotation {
// ...
}
public class MyInterceptor implements MethodInterceptor {
// ...
#Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
//does some stuff
}
}
From what I've been reading it used to be that I could use a #SpringAdvice annotation to specify when the interceptor should intercept something, but that no longer exists.
Can anyone help me?
Thanks a lot!
Lucas
MethodInterceptor can be invoked by registering a Advisor bean as shown below.
#Configurable
#ComponentScan("com.package.to.scan")
public class AopAllianceApplicationContext {
#Bean
public Advisor advisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("#annotation(com.package.annotation.MyAnnotation)");
return new DefaultPointcutAdvisor(pointcut, new MyInterceptor());
}
}
In case anyone is interested in this... apparently this can't be done.
In order to use Java solely (and no XML class) you need to use AspectJ and Spring with #aspect annotations.
This is how the code ended up:
#Aspect
public class MyInterceptor {
#Pointcut(value = "execution(* *(..))")
public void anyMethod() {
// Pointcut for intercepting ANY method.
}
#Around("anyMethod() && #annotation(myAnnotation)")
public Object invoke(final ProceedingJoinPoint pjp, final MyAnnotation myAnnotation) throws Throwable {
//does some stuff
...
}
}
If anyone else finds out something different please feel free to post it!
Regards,
Lucas

Resources