Spring service method validation - spring

I have a service class which is annotated with #Validated.
In this class I have a method with an argument which is annotated with #Valid.
If the method is called from another class instance with an argument that is not valid an exception is thrown.
As expected an error of type ConstraintViolationException is thrown.
If I call this method from another service method (internal call) no validation is performed and an error arises in the body of the method.
This is not what I want. Apparently calls made from within are not validated.
Investigating the problem I found out that the method was not invoked using a Spring proxy bean.
I fixed the problem by retrieving the proxy from the (#Autowired) application context and invoke the method using the proxy:
((T) context.getBean(this.getClass()).myMethod(validatedArgument)
This is an ugly solution.
How can I configure Spring so that method calls made from within are validated?

There is a tricky way to autowire the service to itself.
#Service
public class MyService {
#Autowired
private MyService copy;
private void call() {
//myMethod(validatedArgument);
copy.myMethod(validatedArgument);
}
}

The way Spring handles aspects is such that they are only invoked when one instance sends a message to a different instance. There are some ways to overcome this, but in your case, the fact that you want to do it is probably revealing a design flaw.

Related

How does Hystrix Command annotation work in the application

When I annotated a method with #HystrixCommand Annotation then how is it working
#HystrixCommand(fallbackMethod="getfallBackdisplayDoctorsAndProducts_lipid",
commandProperties= {
#HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="150"),
#HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="25"),
#HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="50"),
#HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="5000")
})
public List<DoctorsAndProducts> displayDoctorsAndProducts(LipidProfile lipidProfile)
{
}
You have your API class and the method inside the API class which is annotated with #HystrixCommand.
Hystrix wraps your API class in a proxy class.
When you ask an instance of API class then the instance of the proxy class will be gotten
The proxy class contains the circuit breaker logics.
When somebody makes a call Hystrix is constantly monitoring that what is returning back.
Proxy class - > get a call and passing to the actual method in the API class and get the response back and examining make sure and returning back.
7.When things fail then the proxy class call fallback method until recovery back.

How control advice catches exception

I am trying to understand how ControllerAdvice is working in SpringBoot. It is suggested that for per application there should be one ControllerAdvice. But my question is how this ControllerAdvice is tied to Controllers and catching the exceptions. So basically what is the underhood?
Spring AOP works with proxies.
That is when you annotate a class with any of AOP annotation spring will create a proxy class by extending your annotated class and all the methods will be overridden there in the proxy class.
Thus here after when you call a method in your class spring will call the proxy object method first then your actual method. This is Spring AOP knows whether the method has been called or thrown some exception or returned successfully etc etc.
This is the reason why when you call a private method with in the class AOP cannot intercept that method call.

Spring MVC #Configuration class constructor

As part of the Spring MVC initialization, I need to run an action (just calling a method on a 3rd party library) once as a setup operation. I'm working in Spring MVC environment where I don't really have control over the web.xml or anything, so I can't add a servlet context listener or anything. I tried making an implementation of a WebApplicationInitializer but it never seems to get called (no idea why though, or how to try and debug that any further).
If I annotate a class with #Configuration it does get created, so I'm wondering if I can use the class's constructor to perform that setup operation (calling a 3rd party setup method). Is this appropriate/safe to do? Are there any other alternatives for this kind of thing? I'm new to Spring, so I might just be missing something that's meant for this kind of thing.
Thanks
Configuration class would be an appropriate place to contain some initialization logic. You can place it in a constructor, method annotated with #PostConstruct or afterPropertiesSet() method if you implement the InitializingBean interface for example. The difference is that the constructor code will be called before the beans in your configuration class are instantiated, so if your initialization code depends on some Spring beans, go with the #PostConstruct / InitializingBean approach.
Example:
#Configuration
public class Config {
#PostConstruct
public void initialize() {
// Run some action
}
}

Invoking custom annotation using Spring AOP

I searched the web for a clear example on how to invoke my custom method annotation using Spring AOP but couldn't find a clear example.
I am building a framework to inject a user profile in the context when certain methods on any POJO is called.
The framework API should be invoked via a custom method annotation, say #RunAsAdmin. I can build the annotation part and parser, my question is what is the best way to invoke my parser when the annotated method is called.
We are using Spring 3.0 and would like to know what is the best practice to configure Spring framework to understand those methods annotated with specific annotation and invoke my annotation handler (parser).
Any example or guidance will be highly appreciated.
Intercepting a call on any annotated Spring bean method is straightforward, see the example below.
Intercepting a call on a POJO is not possible by definition - you have to return a proxy instead.
That is, you should implement a factory for these POJOs that will return proxies instead of real POJOs. You might use ProxyFactoryBean http://docs.spring.io/autorepo/docs/spring-framework/3.2.0.BUILD-SNAPSHOT/api/org/springframework/aop/framework/ProxyFactoryBean.html for this.
//intercepting a call to any method annotated with #com.yours.RunAsAdmin of any Spring-managed bean
#Component #Aspect class RunAsAdminAspect {
#Autowired
private YourRunAsAdminHandler handler;
#Before("#annotation(com.yours.RunAsAdmin)")
public void doRunAsAdmin() {
handler.grantAdminRightsToCurrentUser(); //your real stuff
}
}

#Transactional with static method

Why cant we use #Transactional for static methods to manage the transactions in my spring Project ?
#Transactional works well for non static method but not for static methods any specific reason ?
In order to understand why something like what you are proposing does not work you have to first understand at a high level how Spring handles beans that use #Transactional.
When you annotate a method or the class as #Transactional and make it a Spring Bean, Spring effectively creates a proxy for that class (using JDK Dynamic proxies or CGLIB proxies). That means that whenever your class is used (from Spring managed code that is), it's not your code that gets called immediately, but the proxy which first does whatever is needed, and then your code is called (in the case of caching support your code would perhaps not even be called at all).
A key thing to remember here is that the invoking code (the call site if you will) does not change at all, and the invocation of to the required target method (the proxy method) is performed by the JVM using the same bytecode (invokevirtual or invokeinterface).
With that in mind, the reason that static is not supported becomes clear.
You can't create a proxy for static method! Of course Java Dynamic Proxies cannot do this, and neither can CGLIB.
Supporting such a feature would require changing the bytecode of the invoking code, since calling a static method is implemented via invokestatic in bytecode, which hard-codes the target method.
This part of the Spring documentation explains Spring AOP in details
If you're using AspectJ, here's a simple, albeit ugly, workaround:
public static void doWhatever(final String param) {
new Runnable() {
#Transactional
public void run() {
// do whatever in transaction...
}
}.run();
}
This is feasible using:
#EnableTransactionManagement(mode = ASPECTJ) (or its XML equivalent)
all the configuration required to make AspectJ work
registering a custom aspect to handle #Transactional over static methods like this one I just stumbled upon (did not test it)
NB: in this post I asked about how to make package-private methods #Transactional.

Resources