How to ignore Exceptions during Spring context initialization? - spring

How to configure Spring to continue load its beans, if one of its defined beans in its init method throwed exception. lazy-init="true" option doesn't help - it is just ignored. In this bean init() method i try to open connection with server, which may fail to load the application spring context. Spring 3.0.6

The Idea of Exceptions is to fix the cause of them, not to ignore them.
Have that said: I have never seen anything for that: you have to do it by our own. Put a try catch around the init method that consume the exception and log it.
If you have real AspectJ, then you can use it for that task too. But Spring-AOP will not work.
(comment) I use side library where I should call init method, which establish connection with some server, where problem might appear.
In this case. what about a factory that provides the bean which causes the trouble to the context. The factory should check the connection first (or wait for the exception) (what exactly you do is an implementation detail) and return the bean if every thing is correct. If the connection is failing, then the factory return a Dummy implementation instead..

Related

How to instantiate Spring bean with custom scope and #Autowired dependencies?

In our project, we use Spring request scoped beans. Now we've a requirement to support async requests and request scoped beans don't work for child threads. I'm aware of RequestContextFilter and it's "support" for async but it appears that RequestContextFilter expects the main thread to wait for the child threads to finish, which isn't the case for us. Our main thread immediately returns after spawning new threads using #Async annotation and DispatcherServlet clears out the RequestContextHolder. Thus when the child threads get to the point where they need a request scoped bean, #Autowired fails.
I'm also aware of SimpleThreadScope but it doesn't clean up thread-local attributes and in a thread-pooling situation, is not only dangerous to use but downright useless.
What I need is a custom scope. So far, I've found 3 useful examples but all of them fall short in that the beans they instantiate as part of the custom scope are plain POJOs without any dependencies. Needless to say that's non-existent in a real life application. Can anyone suggest a way to instantiate custom scoped beans that have #Autowired dependencies on beans from other scopes?
What I found so far:
https://github.com/spring-by-example/spring-by-example/tree/master/modules/sbe-thread-scope/src/main/java/org/springbyexample/bean/scope/thread
https://github.com/billkoch/spring-async-mdc
Spring Bean Custom Scope JMS
Continuing the discussion from the other question's answer here...
See the Spring Documentation about scoped beans as dependencies.
.
I'm referring to the <aop:scoped-proxy/> which is what the link points to. Each time the autowired field is referenced, your custom scope's get() method is called to lookup the instance based on some criteria.
.
I understand I can look up the dependencies (though unsure how, a scope isn't a bean, perhaps I need to pass application context during instantiation?). What I don't understand is how to inject those dependencies into my bean if those're marked #Autowired? Or are you saying the custom scoped bean shouldn't have #Autowired dependencies?
It works automatically; Spring injects a proxy for the bean and the scope.get() is invoked on every method call on that bean, returning the specific instance you want in the context of the current invocation.
Take a look at the AbstractRequestAttributesScope to see how it works (in that case, gets the instance from the HTTP Request and, if it doesn't exist, creates it).
So, your code calls foo() on the proxy; the framework calls the scope to get the desired instance and then calls foo() on that instance.
The exposed methods you wish to call must either be on an interface or not declared final.

Graceful handling of exception thrown while creating beans

I want my Spring MVC web app to gracefully handle a particular type of exception thrown while creating the beans.
The construction of one of my beans reads configuration data from an external file. If that configuration data is faulty, one of my bean constructors will throw an exception of a particular type. As the cause of the problem would be a faulty configuration file, I want my web application to respond with a useful log message and/or an error page, rather than a stack-trace of the thrown exception. So I guess I need some kind of exception handler hooked into the IOC container or dispatcher servlet. How can I do that?
Just to be clear. I'm asking about exceptions thrown as the servlet is initialising, not as it handles HTTP requests, so #ExceptionHandler annotations on controllers are not useful.
I worked around this difficulty by introducing a level of indirection. My bean is really just a handle. If the configuration file is bad, the bean catches the exception, logs a message, and notes that reading failed. Accessing the bean later then throws a suitable exception.

Configure a Spring bean callback on server startup?

I want my server to do some database cleanup on startup. I tried adding a #PostConstruct method to a service to do this, however #Transactional doesn't work there. Any changes I make aren't being persisted. How can I get this done? Can I create a new bean with specific callbacks on it?
You can just call another transactional resource in #PostConstruct which does the work, because injection is done then. So DbPopulator can use UserService and whatsoever in its #PostConstruct and everything is transactional and nicely separated again. Singleton beans are constructed at startup afaik, so no additonal setup required.

Using CGLIB proxy with Ehcache CacheManager

I want to use Spring AOP in my spring application. While creating AOP proxy for net.sf.ehcache.CacheManager, spring context initialization fails with the below exception:
nested exception is org.springframework.aop.framework.AopConfigException: Could not
generate CGLIB subclass of class [class net.sf.ehcache.CacheManager]: Common causes of
this problem include using a final class or a non-visible class; nested exception is
net.sf.cglib.core.CodeGenerationException: net.sf.ehcache.CacheException-->Another
unnamed CacheManager already exists in the same VM. Please provide unique names for
each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same
CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: InputStreamConfigurationSource
[stream=java.io.ByteArrayInputStream#955b34]
Here's my understanding about this problem - Spring is trying to create AOP proxy for net.sf.ehcache.CacheManager, and it succeeds the first time and gives a default name to the CacheManager __DEFAULT__ (found this by adding debug statements to ehcache code, building it by source and using that in my application). Now if I've multiple cache managers like 'abcCacheManager' and 'xyzCacheManager' (of type EhCacheManagerFactoryBean), Spring encounters multiple net.sf.ehcache.CacheManagers and tries to create proxy objects (something like net.sf.ehcache.CacheManager$$EnhancerByCGLIB$$b18c5958) for all of them, but with EhCache >=2.5 version, we can't have more than one caches with same name under the same VM.
I'm using EhCache 2.5.1 and would like to avoid going back to 2.4 just for this purpose. I'm not sure if this is really the problem how I can overcome this problem.
Note: Note sure if this will help, but I also noticed from the debug statements that CacheManager no-arg constructor is invoked only by the spring/CGLIB proxy generator and xyzCacheManager invokes it by passing configuration as argument.
Note : I'm answering this myself as it may help others who face the same problem.
jeha's comment on my question makes sense as I shouldn't have needed that proxy at the first place, but since I'm new to Spring AOP and proxies, I didn't know how auto-proxy mechanism works. As I modified the pointcut expressions in my advice, I didn't face the above problem after that. Prior to this, almost all the beans in the container were getting proxied and hence the problem.

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