Does Spring wait for each #PostConstruct to finish when loading ApplicationContext - spring

I have some logic of loading data from the DB in #PostConstruct method in some of the service classes which takes a long time.
And there are some unrelated controllers which load quite quickly and could potentially start accepting HTTP requests.
So the question, does Spring just wait for each #PostConstruct method to return when loading the ApplicationContext, hence can't accept any requests, or are there any exceptions?
I know, I could load the data from DB asynchronously, but perhaps there're brighter solutions?

In Spring all the REST endpoint are actualized through RequestMappingHandlerMapping class.
And this kicks in after #PostContruct. So the way you are doing is perfectly fine.

Related

Spring: Side effects of #Async on Transactions handling?

I have a Spring Boot REST API through which a web client can start the execution of a testsuite. The handling of the transactions was tricky, but i finally made it and everything work as expected. This is my setting:
the http request is handled by a controller (1)
when receiving the request, the controller publishes an event "start testsuite" (I use the Spring Event handling)
a method with #EventListener (2) listens to that event and calls the method in charge of the testsuite execution (3).
Now it turns out that the execution of the testsuite is sometime very long. As I don't want the http request to remain pending too long, I'd like to make the testsuite execution asynchron. To achieve that I added a #Async at the method of the service layer in charge of the testsuite execution(3).
As a result: I can tell that the process runs now indeed async but the testsuite execution behave in a weird way that make me think the transactions are not handled correctly anymore. So what I'm trying to understand, and that's the object of this question: in which way the #Async can, in this configuration, have side effects on the transaction handling?
I did some research. According to this article
If the #Async annotation is being used extra care should be taken with respect to transactions. In normal circumstances (without #Async) a transaction gets propagated through the call hierarchy from one Spring #Component to the other. However, when a #Transactional Spring #Component calls a method annotated with #Async this does not happen. The call to the asynchronous method is being scheduled and executed at a later time by a task executor and is thus handled as a 'fresh' call, i.e. without a transactional context. If the #Async method (or the #Component in which it is declared) is not #Transactional by itself Spring will not manage any needed transactions.
I get that point, but I don't think I'm in this situation since the calling method of the async method (= the event listener) has not been made transactional.
Does anyone have a clue?

Understanding Spring AOP and Transaction Aspect

I was studying about the Proxy Object which spring gives when we autowire any interface. This is a very good link for understanding that https://www.youtube.com/watch?v=bEvGdWjeCy4&t=310s. Here he explains that If a POJO implements any interface then Spring proxy bean also implements that interface (using JDK Proxy mechanism) and adds additional logic such as transactional logic (if the method was annotated using jdbc code or delegating it to PlatformTransactionManager). Spring gives us a wrapper object which has the reference to the real object and it has additional code which it runs before and after the original method is invoked using MethodInvocationHandler. So My question is that how exactly spring is managing that transaction.Where that jdbc code to get connection and start transaction is written. Is it in the Spring Proxy object or any Aspect Class.
As in AOP there as Aspects which are basically the cross cutting concerns such as transaction common to the whole application. Is Spring inserting Transaction behavior code in the Proxy Object or is it Using PlatformTransactionManager to do that And Where does This AOP fits in this Flow. How the Aspect handling Transactional behavior getting invoked here if it is. How the call is getting transferred to it?
In term of JDK proxy , you have to supply a InvocationHandler implementation when creating a proxy object. When the proxy object is invoked , this InvocationHandler will be invoked around the actual object. (see this for a hello world example for how does JDK proxy works)
In term of the spring transaction , it already shipped with an InvocationHandler implementation (i.e. JdkDynamicAopProxy). It will then somehow invoke the transaction aspect (i.e. TransactionInterceptor). The transaction aspect is responsible for controlling the whole workflow such as when to create , commit or rollback the transaction and when to actually execute the actual method etc.
The transaction aspect also delegates to the PlatformTransactionManager to actually start , commit and rollback a transaction. Because different technologies has their own ways to start , commit and rollback a transaction , it is necessary to introduce a PlatformTransactionManager as an interface to abstract these operations such that we can switch different transaction technology by simply switching the PlatformTransactionManager implementation inside the transaction aspect .
So back to your questions :
Where that jdbc code to get connection and start transaction is
written. Is it in the Spring Proxy object or any Aspect Class.
None of them. It is actually the PlatformTransactionManager to get the connection and start the transaction which is invoked by the aspect.
Is Spring inserting Transaction behaviour code in the Proxy Object or
is it Using PlatformTransactionManager to do that And Where does This
AOP fits in this Flow.
Spring inserts the transaction behaviour in the aspect object (i.e. TransactionInterceptor). The aspects then delegate to the PlatformTransactionManager to actually start , commit and rollback the transaction.
How the Aspect handling Transactional behaviour getting invoked here
if it is. How the call is getting transferred to it?
Assuming the JDK proxy is used , the call flow is something like :
Someone invokes on the JDK proxy
InvocationHandler of this proxy will be invoked (i.e JdkDynamicAopProxy)
InvocationHandler somehow calls spring transaction aspect (i.e TransactionInterceptor)
Transaction aspect delegates to PlatformTransactionManager to actually start , commit and rollback the transaction if necessary.

Lazy loading works, but shouldn't

The context of this question is within spring-boot, using spring-data-jpa and hibernate.
A colleague wrote an #Service and annotated the service method with #Transactional. The service method loads an entity, and subsequently hits a one-to-many lazily loaded collection (fetch = FetchType.LAZY). The service method is invoked by some custom delegator, which i will come back to. This works fine when invoked from a #RestController endpoint.
When i invoked the service from a camel route (again via the custom delegator) it barfed with a lazy initialization exception.
On digging, found that the service implements an interface, the custom delegator looks up the service (it is injected so has proper proxy) and calls a method
on the interface which is actually a java-8 default method. This default-method then locally calls the #Transactional method.
So there's the problem :- this is a LOCAL method call so the aspecting/proxy-ing of the #Transactional annotation is not done (we use aspectJAutoProxy) so the method is NOT invoked within a transaction, so the lazy-loading SHOULD fail. And to double-check, also tried it via an #Scheduled annotation: same behaviour. Barfs like it should.
My Question: So why does it work when called from the #RestController? This is driving me nuts!
There is no transactional annotation on the rest controller endpoint.
I added some debug code to the service using TransactionSynchronizationManager.isActualTransactionActive() and it shows that in no case is there a transaction, even when being called via the controller endpoint.
So why does the lazy loading work when being called from the controller?
I dumped all SQL and at no points are the lazy-collection already loaded, so they are not in any hibernate cache.
I remember reading once that lazy loading was a hint, not a command, but still... why does it work in that one case?
after being perplexed by this on many occasions, have stumbled across the answer:
sprint-boot is doing an open-entity-manager-in-view behind our backs via the OpenEntityManagerInView interceptor. Had no idea this was going on.
See this excellent answer from Vlad Mihalcea https://stackoverflow.com/a/48222934/208687
When your method annotate to transactional hibernate session close after return method , if object that return from method have lazy , lazy property not load and you get exception that session close. You can use fetch in query or using OSIV

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.

Spring DefaultAdvisorAutoProxyCreator with #Transactional causing problems

I'm working on a Spring MVC project and trying to integrate Apache Shiro for the security. Everything was going just swimmingly until I realized Hibernate was prematurely closing the session/connection after a single query and causing a lazyinit exception. Not surprising, what I was doing should be done within a transaction so the session isn't closed.
Dilemmas…
I tried putting #Transactional on my controller method, but I get 404's then. Looking at my logs, I can see that when Spring is bootstrapping it ignores any mappings in my HomeController if that #Transactional annotation is on any method within the controller.
Without the #Transactional and it loads up just fine, and Ih can see the RequestMappingHandlerMapping bean sees all the #RequestMapping annotations in my controller.
With #Transactional but without DefaultAdvisorAutoProxyCreator, and it works except Shiro annotations are simply ignored.
tldr: Shiro requires DefaultAdvisorAutoProxyCreator, but if I create that bean, Spring blows up when using the #Transactional annotation.
I'm asking for help because I'm completely at a loss for how to proceed at this point.
This is typically because when you put #Transactional on a method, Spring creates a dynamic proxy for that bean - if the bean implements an interface then dynamic proxy is created based on that interface, otherwise CGLIB will be used for creating the proxy.
The problem in your case, I am guessing is because you probably have based your controller on some interface, or you are extending it based on a base class. This is ending up creating a proxy based on that interface, because of this when it comes time for mappings to be created for your request, Spring MVC is probably not finding your mappings from your bean.
The fix could be a few:
a. You can try and force proxies to be based on CGLIB for your transactions:
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
b. You can use pure Aspectj,either load time weaving or compile time weaving
c. You can move the #Transactional into a Service (which has an interface) and delegate the call from the controller to the service, this way avoiding #Transaction on the controller

Resources