Grails 2.3 strange plug-in eager loading behavior - spring

I've just added a custom local plug-in (via 'grails.plugin.location...' build config declaration) to a grails 2.3 project. As soon as I add the plug-in and try to run my application I see a strange behavior whereby all of the beans in my main application suddenly try to eagerload across the board. I.e. if I have:
class FooService {
BarService barService
}
class BarService {
FooService fooService
}
Then the application cannot start. There is no code being executed in FooService or BarService at init time that should cause the Spring context to need to unwrap the either fooService or barService instance but that behavior seems to be happening anyway. In the end the application init fails with an exception like:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'fooService': org.springframework.beans.factory.FactoryBeanNotInitializedException: FactoryBean is not fully initialized yet
As the fooService requires the barService, which requires the fooService which is still being created.
As soon as I remove the dependency on the custom plug-in then the problem stops. Obviously something either in the plugin or about the plugin (meta data or something) is causing this behavior but I can't figure out what exactly.
Rather than a solution I think what I am looking for here is some trouble-shooting techniques or information leading me to understand why this eagerloading behavior is occurring. I just don't know what the right hooks/configs are that will let me get in the head of the Spring context initialization mechanism.

I found the answer to my question buried deep in the comments of this other SO question: Grails service using a method from another service
Basically my plugin introduced the hibernate plug-in into my project and therefore also introduced transactional-by-default services. This transactional bootstrapping was causing the eager load of all dependencies and thus my circular dependency problem.
The fix was to, at least for now, mark the circularly dependent services as non-transactional. Of course in the future if I need those services to be transactional it seems I will need to re-architect my service setup.

Related

#SpringBootTest loads unrequired Bean when making IT

I'm making some Integration Tests for my app and I'm encountering this problem I can't see how to solve.
I'm using Spring Boot 2.4.13 + Spring Data Neo4J 6.1.9
FYI, I deleted the Application default test that comes bundled when you create a project through Spring Initializr, and under /src/test/resources I have a .yml file named application.yml
My IT class looks like this:
#SpringBootTest
public class ClientIT {
#Autowired
private ClientServiceImpl service;
#Autowired
private ClientRepository repository;
#Test
void someTest() {
//Given
//When
//Then
}
}
But when I run this test I get the following Exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
And this is the cause:
Caused by: java.lang.IllegalStateException: The provided database selection provider differs from the ReactiveNeo4jClient's one.
The thing is I don't use SDN's Reactive features at all in my project. I don't even understand why Spring tries to load it. I've created an Issue under the Spring Data Neo4j GitHub repository (https://github.com/spring-projects/spring-data-neo4j/issues/2488) but they could only tell me that ReactiveNeo4jDataAutoConfiguration gets automatically included if there's a Driver or Flux class in the classpath which I don't have.
I've been debugging the Spring internals while booting up the Application after JUnit Jupiter methods to no success.
What I could see is that at some point after JUnit Jupiter tests preparation/initialization, "reactiveNeo4jTemplate" gets injected into DefaultListableBeanFactory's beanDefinitionNames variable.
I've tried many combinations of different annotations intended to be used when making Integration Tests but the one time it worked was after I explicitly excluded ReactiveNeo4jDataAutoConfiguration class through
#EnableAutoConfiguration(exclude=ReactiveNeo4jDataAutoConfiguration.class)
What I've always seen in some blogposts is that by using #SpringBootTest I shouldn't worry about this kind of problem but it looks like I need to add that annotation every time I want to make a new IT test.
My Integration Tests basically consist of bootstrapping the application + web server (tomcat) along with an embedded Neo4J instance and after that, making requests to check everything works as it should. Do I really need to worry about all of this just to make these simple tests?
Thank you
References:
How do I set up a Spring Data Neo4j integration test with JUnit 5 (in Kotlin)?
SprintBootTest - create only necessary beans
Answering my own question after finding what is causing this error:
In the linked Github Issue, one of the developers says having Flux.class in the classpath forces SDN to instantiate Neo4jReactiveDataAutoConfiguration which is what is causing the other reactive beans to instantiate.
Apparently, neo4j-harness brings io.projectreactor (where Flux.class belongs) as an indirect dependency through neo4j-fabric which is the root of our problems.
The Spring Data Neo4j will be fixing this issue in a patch later this week.

How to force MongoMappingContext to be created via MongoDataAutoConfiguration.mongoMappingContext()?

I'm having an issue with my #Document classes not being discovered at start up and it appears to be because the MongoMappingContext isn't created via MongoDataAutoConfiguration (which would scan for the #Document classes) since it's already been defined elsewhere. By setting breakpoints, it appears that MongoMappingContext is instantiated as part of the creation of MongoTemplate by the application context.
I'm puzzled because it seems like using repositories in any way would cause this to occur so I don't see how the method would ever be called.

Does ComponentScan order matter?

I'm setting up a very small Spring/REST/JPA project with Boot, using annotations.
I'm getting some Bean not found errors in my REST controller class that has an Autowired repository variable, when I move my JPA repository class out to a different package, and calling componentscan on its package. However, everything was working fine when all my files(5 total) were in the same package.
So I was wondering, however unlikely, if the component scan order matters? For example, if a class is AutoWiring some beans from a package that has not been 'component scanned' yet, will that cause a Bean not found error?
No, Spring loads all configuration information, from files and annotations and the environment when appropriate. It then creates beans (instances of classes) according to a dependency tree that it calculates in memory. In order to do this it has to have a good idea of the entire configuration at startup. The whole model derived from all the aggregated configuration information is called the Application Context.
In modern versions of spring the application context is flexible at runtime and so it's not quite the case that all the configuration is necessarily known up front, but the configuration that is flexible is limited in scope and must be planned for carefully.
Maybe you need to share some code. When you move that stuff, you also need to tell Spring where they went. My guess would be you haven't defined #EntityScan and #EnableJpaRepositories (which default to the location of #EnableAutoConfiguration).
There could be several problems:
You moved your class out of the some package where you have #ComponentScan without arguments. That basically means that components are scan only in this package and its children. Thus, moved class are not scanned and there is no bean to wire.
Wrong package name in #ComponentScan args.
The order isn't matter at all. There is an #Order annotation, but it's purpose is more about loading multiple implementations of sth in a different order.
At first Bean Definitions are created and they have nothing to do with wiring. Then via bean post processors, autowired beans are injected. Since there were no bean definition. There is nothing to inject.
In a well structured program it doesn't, because first each bean gets instantiated, then autowired and then you can actually use them.
However there could be situations where the order does matter and I had an issue figuring out what was going on. So this is an example where it would matter:
You have some Repository that you want to fill with data initially, call it SetupData component.
Then you use #PostConstruct to save the default objects.
You have some component that this Repository depends on but isn't managed by Spring, for example a #Converter.
And that #Converter depends on some other component which you would statically inject.
In this case #PostConstruct methods will be executed before the components into your #Converter get autowired which will result in an exception.
Relying on ComponentScan order is a bad habit, because it's not intuitive especially when you are working with multiple people who may not know about. Or there might be such dependencies that you can't fix the code by changing the scan order.
The best solution in this case was using a task executor service that takes care of running initialization functions.

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.

Access application context from BundleContextAware class

I have created an osgi bundle from an existing legacy war. The app has a class that implements the spring interface ApplicationContextAware, it then uses the context to programmatically get beans (not sure why but this needs refactoring eventually). The app now uses OsgiBundleXmlApplicationContext, but I believe that there is an issue with using this whereby the setApplicationContext method does not get called in any classes implementing ApplicationContextAware, so now the context in this class is always null.
So as a workaround I have implemented BundleContextAware so that I can get a reference to the published context and get access to the beans that way. This works ok however the only bean on the context is warDeployer (should mention that I am using the spring dm bundle spring-extender to deploy the war). The bundle present on the context is my bundle so I cannot see why the context that I am getting has none of my beans on it. The code I have to get the application context is:
ServiceReference ref = bundleContext.getServiceReference(ApplicationContext.class.getName());
applicationContext = (OsgiBundleXmlApplicationContext) bundleContext.getService(ref);
I can see in the logs that much of my context is getting created so I can't see why they are not on the context I am getting.
Can anyone advise as to what is wrong? I understand that this approach is a bit hacky, but it's temporary until the existing code is refactored.
Thanks in advance.
Barry
I believe that the ApplicationContext service is registered asynchronously by the Spring-DM extender. So you probably have a race condition, i.e. asking for the service just before it is actually registered.
You could introduce a delay but then you're very deep into nasty hack territory. It would be better to work out why the setApplicationContext method on the ApplicationContextAware beans is not being set. You should try raising this is a bug against Spring-DM or asking in the Spring-DM Google Group.

Resources