Is an explicit CacheManager bean definition mandatory when using Spring Boot + Spring Cache? - spring-boot

From documentation Spring Boot uses ConcurrentMapCacheManager as CacheManager implementation by default if we don't define own CacheManager bean definition. But I keep getting 'No qualifying bean of type 'org.springframework.cache.CacheManager' available' error eventhough spring-boot-starter-cache and #EnableCaching is there.
Any help would be greatly appreciated.
Best regards,
SetNug

Short answer... NO.
I suspect you are having problems while (integration) testing? If so, then you probably need to declare the appropriate "test slice annotation", that is #AutoConfigureCache; see Javadoc.
To demonstrate, I created a simple example with a test class contained in this module of my SO repository. You must declare the #AutoConfigureCache annotation in configuration (see here) even if your test is a #SpringBootTest.
As Spring Boot's documentation describes, all of Spring Boot's auto-configuration (which is quite extensive) can be a bit much for testing. As such, none of Spring Boot's auto-configuration is enabled by default. Therefore, you must explicitly enable what you want, or, alternatively, you can declare that you want Spring Boot's entire auto-configuration enabled, by replacing the #AutoConfigureCache annotation declaration with Spring Boot's #EnableAutoConfiguration annotation instead.
You are correct that Spring Boot will auto-configure a "Simple" caching provider (i.e. the ConcurrentMapCacheManager, or in other words, a Spring CacheManager implementation backed by a java.util.concurent.ConcurrentHashMap; see here) when no other cache provider implementation (e.g Redis) is present or explicitly declared.
However, Spring Boot auto-configuration is only in effect when your Spring Boot application is an "application", which I have shown here.
Of course, it is also true that if your #SpringBootApplication annotated class is found (in the classpath component-scan) by your test as described, then it will also enable caching without any explicit annotations, such as, no need to explicitly declare the #AutoConfigureCache test slice annotation, even.
NOTE: In my example, I deliberately did not package the source according to the suggested structure. So, if I were to replace the #AutoConfigureCache annotation declaration in my test configuration with #Import(SpringBootDefaultCachingApplication.class) and comment out this assertion from the application class, then the test would also pass. Using the #Import annotation in this way works similarly as if the test class and application class were in the same package, or the application class were in a parent package relative to the test class.
1 last tip... you can always enable Spring Boot debugging (see Baeldung's blog) to see what auto-configuration is applied while running your application, or even while running tests.

Related

How to load PropertySources sooner in Spring Boot

I have currently a problem in my DEV environment. I have for Spring Security two configurations, one for the Admin part of my application and the other for the rest of the user. For the admin part, I create one or another depending on beans decorated with a Conditional annotation. This conditionals rely on some property that is loaded from a class that is annotated with #PropertySource and this is important, this property I cannot set it neither in application.properties nor application-<environment>.properties. The problem comes that when these conditionals are evaluated because are spring security classes, the properties that are expected to perform such evaluation are not available, they come in a later stage, when Spring boot do some refresh context. My question is how I can do it do this class annotated with #Configuration #PropertySources to be loaded much sooner, right after the Profile is processed.
Thanks in advance.

Implementation provided for BatchConfigurer is not connsidered when using #EnableBatchProcessing(modular=true)

I am developing a sample application that Spring Batch with Spring Boot. My requirement is:
Have my own implementation of BasicBatchConfigurer so that I can configure AsyncTaskExecutor and my own dataSource as I am using SAP HANA as DB for which databaseType is not supported.
I want to use #EnableBatchProcessing(modular=true) so that I can register multiple jobs and launch them with separate Child Context
I have added all the required configurations. Without setting modular=true the Job is Launched and works as expected. It initializes the beans defined from my implementation of BasicBatchConfigurer.
However, once modular=true is set, the beans from my implementation are not initialized.
The code is hosted here: https://github.com/VKJEY/spring-framework-evaluation
I debugged further into the issue:
Looks like, When we set modular=true, BatchConfigurationSelector uses ModularBatchConfiguration
In ModularBatchConfiguration, there's a field Collection<BatchConfigurer> configurers. This has been annotated as #autowired.
I assume that this field is auto initialized if I provided a implementation
of BatchConfigurer as it has been mentioned in the comments of ModularBatchConfiguration class as well
However, While debugging I realized that the above field is still null beacuse of which, It loads DefaultBatchConfigurer and follows the default flow.
My question is why is that field configurers not being initialized in ModularBatchConfiguration? Am I missing something?
I am using Spring boot 2.1.2.
My question is why is that field configurers not being initialized in ModularBatchConfiguration? Am I missing something?
You are hitting a lifecycle issue between Spring Boot custom auto-configuration that you defined in the META-INF/spring.factories file and Spring Batch configuration.
I debugged your code and here is how to fix the issue:
remove org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.job.data.persistence.config.AsyncBatchConfigurer
from META-INF/spring.factories file. This is not needed as Spring Batch
will detect the AsyncBatchConfigurer when it is declared as a bean.
You can even remove this spring.factories file
remove #ConditionalOnMissingBean(BatchConfigurer.class) from AsyncBatchConfigurer:
Since you declared this class as a #Configuration class, it will also be defined as a bean of type BatchConfigurer and will be detected by ModularBatchConfiguration
With these two changes, the field configurers in ModularBatchConfiguration is correctly autowired with your AsyncBatchConfigurer.
As a side note, you don't need the AsyncBatchConfigurer#configurers method as Spring will do the work of injecting all BatchConfigurer beans in ModularBatchConfiguration.
Hope this helps.

Spring Boot - Load bean only if it is enabled by a property

I have a Spring Boot application with different submodules which also contains spring components.
And in the main web modules I use 70% of the beans from the submodules. It depends on the application.yml properties, if the property group (which points to a bean) is enabled or not.
First I wanted to create Aspect-s, so when a method of a bean (which is not enabled by it's property) is called, then throw an exception. This solution could work, but then I would need to create Aspect classes, method annotations, import more and more dependencies.
So I am just wondering, would be there any other easier solution to disable a bean, or do not load at all to the spring boot container?
I would imagine something like #DependsOn, but for this you need to give a name of a bean name, but you cannot use this annotation to work with yml property.
Other easy solution is to #Bean or #Import every bean I want to managed by spring container, instead of #Import everything once from submodules, but then it is a static setting, cannot be overwrite by a single property from yml.
Spring introduced the concept of conditionals quite some time ago. Spring Boot uses this to a great extend to conditionally enable features. It even created a lot of conditional rules which you can use.
One of those rules is the conditional on a property rule. To use this rule add an #ConditionalOnProperty annotation to your bean. Now it will only be included if said property is enabled or has the specific value.
#ConditionalOnProperty(name="your.property.name")

Java EE 6 / 7 equivalent for Spring #Configuration

Is there a Java EE 6 / 7 equivalent annotation for Spring's #Configuration?
If the answer is yes then are the equivalents for its surrounding annotations, such as #ComponentScan and #EnableWebMvc?
I did, of course, look for it in Java EE 6 / 7 (I admit I skipped a paragraph here and there), in javadocs (specifically among annotations), in Spring doc, tutorials, blogs, SO and Google.
JEE CDI has also an annotation of creating bean programmatically and exposing them, so it offers bean factories, called producers:
https://dzone.com/articles/cdi-and-the-produces-annotation-for-factory
CDI offers Producer methods (annotated with #Produces) which is the equivalent of #Bean in spring. You can than implement Producers classes that are beans which contain a bunch of producer methods. However, this is by far not as powerful as a spring configuration since as far as I am aware of, there is no possibity to e.g. "import" other configurations (producer classes).
This makes it especially difficult to test CDI applications.
You can either
heavily use mocks to test a single CDI bean to totally avoid injected objects
blow up your test class just to create the instance under test with all dependencies
use testing frameworks like CDI-Unit that creates the beans for you
With 1. Test Driven Development becomes almost impossible and tests have always to be adapted when implementation changes, even if the contract does not change.
With 2. you end up in a lot compiler errors in tests as soon as dependencies between your Beans change
With 3. you need to point your testing framework to the implementation of your beans. Since there exists no Configuration that knows about all beans, the test needs to know about it. Again, if things change your tests will break.
I admit... I don't like CDI ;-P
The javax.servlet.annotation package defines a number of annotations to be used to register Servlet, Filter, and Listener classes as well as do some other configuration, for example, security.
You can also use the ServletContainerInitializer class to configure your ServletContext through Java instead of through the XML deployment descriptor. Spring provides its own implementation of ServletContainerInitializer in which case all you have to do is create a class that implements WebApplicationInitializer and does servlet, filter, and listener registration and leave that class on the classpath.
Examples abound in the javadoc.

Spring-data-mongo: MongoRepository not being wired unless I add #Component annotation

I am having a little weird behavior with my spring-data-mongo where my repository package is not being scanned by the <mongo:repositories/> tag. I am using spring 3.2.3.RELEASE with spring-data-mongo 1.2.1.RELEASE.
I have a project called edowmis and in it there are 2 maven modules, datalayer and web which a webapp.I am using the datalayer in isolation so the other module can be ignored. I have an application context for datalayer
So I wanted to test my setup by writing a small Unit/Integration test but I've noticed I can't autowire my UserRepository because It says there isn't such a bean
Since I am using IntelliJ I can see certain visuals when things are ok and not ok. I've addec <context:component-scan/> to my application context but no result.
But when I add the #Component annotation it has started identifying the Class.
all information you might need is on pastie.org
Is the #component or #Repository really necessary or something is wrong with my configuration?
Yes, the #Component or #Repository is necessary. The scan simply indicates that spring should look for classes identified via annotations (#Component, #Repository, #Service) and load them as beans. If you don't use repository or component scan, you would have to manually instantiate all spring-managed beans via XML configuration or Java configuration.
You have to tell spring which classes to turn into beans as it doesn't assume everything in the classpath is supposed to be a spring-managed bean, which is why you need to use the annotations.

Resources