Automatic invocation of Bean Validator for #Valid outside of Spring MVC - spring

Simple scenario:-
In a Spring 4 app the following #Valid gets triggered when I make a REST call but not when I make an API call. The docs talks about it but does not state how to do it the way I want.
#RequestMapping(name="/something")
public Entity save(#Valid Entity e){ return repo.save(e);}
Without writing any custom AOP code to achieve this myself etc. how do I get bean validation #Valid triggered in Spring ? Looking for any Spring or Hibernate configuration that will turn this on for simple API calls.
Example: When I bundle my component as a maven I would like to get my beans validated irrespective of whether they run in a web context or outside , say Spring Batch or just JUnit Tests.
And when I bundle this jar in a web app I definitely don't want this executed twice.

Related

Spring Boot Best approach for validation in facade

I use Spring Boot with Kotlin and my project is splitted on modules where I have application layer with REST controllers and facades, domain layer with services and business logic and infrastructures layer for communication with external services or DBs. I think (but I can be wrong) that the best place for basic validation like notNull, notEmpty, max and min, size etc. is facade because both REST controllers and another modules communicate with it, but the problem is that javax validation annotation like #Valid are working only on REST Controller layer (in classes with annotation #RestController) and when I try to create some tests for this facade then fields with wrong values return NullPointerException instead of MethodArgumentNotValidException. I tried to create WebMvcTest but also returns wrong exception. Is it some solution for it? I saw that I could call some validator inside the method but it looks like much more complex approach than annotation on method's argument.
You can inject the javax.validation.Validator into any Spring component. For example, into a facade component, and perform validation in the facade layer:
#Autowired
Validator validator;
Set<ConstraintViolation<UserRequestDTO>> violations = validator.validate(userRequest);
This way you can remove the #Valid annotation from controllers at all. And this approach puts validation results under the your control.

#Transactional doesnt work whereas DefaultTransactionDefinition works

I am upgrading my application from Spring3 to Spring 4. In my existing application we were using OpenSessionInViewInterceptor which creates the transaction along with new request.
Now I am using JPA also so even if I use OpenEntityManagerInViewInterceptor it doesn't associate transactions with it. So I had to put transaction manually in all my controller methods.
Due to legacy code, the controller classes have lots of business logic instead of distributing it properly to service layer.
Now if I put #Transctional annotation on controller method, then it doesn't work whereas if I use manual transaction through DefaultTransactionDefinition then it works properly.
Also, if I remove the business logic of controller methods to service layer, and put #Transactional annotation to service layer, then it also work fine. But these changes are tedious and my application is very big, so cant do it.
Please let me know why #Transactional doesn't work in my case if I put it in controller, how should I get it working.
I am not using AspectJ for transaction management.
Tried approaches:
Code at both places : code in dispatcher-servlet.xml along with appliacationContext.xml but still the controller transactions are failing.
Moved bean for urlMapping into applicationContext.xml but still it fails.

Calling hystrix command in fallback method

I am planning to use the hystrix command to publish a message to rabbitmq. If the publish fails for whatever reason, i want to fallback on a webservice call. Now i also want this webservice call to be protected by hystrix. If this call also fails, i want to log the exception and abort. I am using spring boot with hystrix annotations. My understanding is that hystrix command cannot be applied on fallback method. Instead we have to create a new spring component class with a method annotated with hystrixcommand and inject it and use it in the fallback method. Is this the only way or is there a simpler way to do this without creating a new class?

Invoking proxied DAO methods from Spring stand alone client :- could not initialize proxy - no Session

I have a third party jar in my class path which has some services and DAO's developed on top of Spring 2.0.6 and Hibernate3.2.6. I need to call some of the services and daos.
Using ClassPathXmlApplicationContext I'm able to load the application context and able to access the services and daos. Both the service and dao are following ProxyFactoryBean pattern.
Problem comes when I'm accessing a DAO which has some single valued associations.When I'm accessing associated entity I'm getting lazy initialization problem.
To solve this problem:- If it is in my own application JAR I'll be able to change the fetch type into join or in DAOImpl method I could use Hibernate.initialize().
Is there a way to avoid this problem from the stand alone code itself? Or any other way to solve this issue without modifying applicationContext.xml and DAOImpl
You need to put the caller method into one single transaction.
If you have Spring transactional environment, you can put the call of the DAO services/repositories in your own service/method which is marked as #Transactional, or if transaction support is not enabled, but you still have spring support in your application, you can just use TransactionTemplate directly, provided by spring
#Autowire
private PlatformTransactionManager txManager;
TransactionTemplate template = new TransactionTemplate(this.txManager);
template.execute( new TransactionCallback<Object>(){
public void doInTransaction(TransactionStatus status){
// work done here will be wrapped by a transaction and committed.
// status.setRollbackOnly(true) is called or an exception is thrown
}
});
Otherwise you have manually handle transactionality by your own , depending on the technologies your app is using.

Testing injected dependencies into your struts2 actions

I am wondering how others might have accomplished this. I found in the Spring documentation #required which I attempted to use in a 'test' but got this stmt INFO XmlConfigurationProvider:380 - Unable to verify action class [xxx] exists at initialization
I have found another way in spring to do this is to write custom init methods and declare those on the bean but it almost seems like this is a strange thing to do to a struts2 action.
In my application I inject through spring different web services (via setter injection) into different actions. I want to ensure on startup these are not null and set.
Use request or session spring scopes.
Then you can do the checks in a #PostConstruct method, what will you do there? Throw an exception? Well, something isn't set you will eventually get a NullPointerException.

Resources