Can't config Java Spring Boot data session Mongodb - java

I've been using this guide to set up spring session data with mongodb
https://docs.spring.io/spring-session-data-mongodb/docs/2.1.1.RELEASE/reference/htmlsingle/#introduction
However I am having problems with configuration. I'm using Mongodb with Spring boot and I'm trying to config my session time and session name for Spring boot web application, but it keeps defaulting to 30 minutes and the collection name in mongodb is still 'sessions'
These are what I have tried:
Added these to application.properties:
server.session.timeout=1
spring.session.mongodb.collection-name=TestSESSIONS
and this
server.servlet.session.timeout=60s
spring.session.mongodb.collection-name=TestSESSIONS
none of those config work
I've looked over this URL for spring common application properties for mongodb but none of it help to config the session time and collection name for mongodb.
After doing hours of research it seems like spring boot uses some kind of autoconfig with this "org.springframework.boot.autoconfigure"
so then I added this in my application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
to disable the autoconfigure.
but now it just give me this error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method mongoSessionRepository in org.springframework.session.data.mongo.config.annotation.web.http.MongoHttpSessionConfiguration required a bean of type 'org.springframework.data.mongodb.core.MongoOperations' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'mongoTemplate' in 'MongoDataAutoConfiguration' not loaded because AnyNestedCondition 0 matched 2 did not; NestedCondition on MongoDataAutoConfiguration.AnyMongoClientAvailable.FallbackClientAvailable #ConditionalOnBean (types: com.mongodb.client.MongoClient; SearchStrategy: all) did not find any beans of type com.mongodb.client.MongoClient; NestedCondition on MongoDataAutoConfiguration.AnyMongoClientAvailable.PreferredClientAvailable #ConditionalOnBean (types: com.mongodb.MongoClient; SearchStrategy: all) did not find any beans of type com.mongodb.MongoClient
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.data.mongodb.core.MongoOperations' in your configuration.
this is the #bean from the spring.io guide 'mongoSessionConverter' from above link
this is the java file MongoHttpSessionConfiguration from spring that that's autoconfig by spring; I have tried extending "MongoHttpSessionConfiguration" and overriding the setter methods my self. Such as the "setMaxInactiveIntervalInSeconds" for sessionTime and
"setCollectionName" for mongododb database collection name.
but I've have this error:
Description:
The bean 'mongoSessionRepository', defined in class path resource [com/khatpass/app/config/SessionListenerConfig.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/session/data/mongo/config/annotation/web/http/MongoHttpSessionConfiguration.class] and overriding is disabled.
I am stuck on trying to configure spring boot session with Mongodb. The session always defaulting to 30 minutes and the collection name is always 'sessions' in mongodb collections. Not sure how to change that serverSelectionTimeout='30000 ms' and mongodb collections name "sessions" I don't know what to do, need help.
2019-02-24 13:39:54.501 INFO 36113 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

After doing so much research and then finally, going through the source code, I found the solution:
#EnableMongoHttpSession(maxInactiveIntervalInSeconds = 24 * 60 * 60)
public class SessionConfiguration {}
To override the default collection name, there is another annotation attribute collectionName.
This is working for Spring Boot 2.1.1

After looking over the class MongoOperationsSessionRepository from org.springframework.session.data.mongo it seems like it can't be config through application.properties because the class is using static final values
public static final int DEFAULT_INACTIVE_INTERVAL = 1800;
and
public static final String DEFAULT_COLLECTION_NAME = "sessions";
only way to change the value is intercept the object before it gets saved. No getters or setters for those fields, it can't be change in an easy way, what a joke!

Related

sql scripts not working when JobRegistryBeanPostProcessor bean is used

I have a Spring batch application which uses some sql scripts to initialise the database.
When I extend the application by Spring Batch functionality I need to instantiate the JobRegistryBeanPostProcessor bean in order to use JobRegistry.
I use a similar method as in https://github.com/jbbarquero/spring-batch-sample/blob/master/src/main/java/com/malsolo/springframework/batch/sample/BatchConfiguration.java
However with such addition I have got a problem - sql scripts are not executed anymore.
In the log output I mentioned such new INFO messages with different bean names (XXX) :
] trationDelegate$BeanPostProcessorChecker : Bean XXX is not eligible
for getting processed by all BeanPostProcessors (for example: not
eligible for auto-proxying)
Is there an approach to resolve the problem aforementioned ?
There is a following solution to the problem:
instead of instantiating the JobRegistryBeanPostProcessor bean, directly register the job in the jobRegistry as proposed in https://stackoverflow.com/a/53381283/6931863
Such solution enables initialisation of Database from data.sql as well as stopping jobs using jobOperator.stop.

Field repository in com.petar.demoreferrals.service.impl.UserServiceImpl required a bean

I am trying one basic spring boot demo.
I am getting this error.
...
I don't know which code to copy so here is link from the demo https://github.com/PetarRistevski/demo-referrals
This is what I get
APPLICATION FAILED TO START
Description:
Field repository in com.petar.demoreferrals.service.impl.UserServiceImpl required a bean of type 'com.petar.demoreferrals.repository.UserRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.petar.demoreferrals.repository.UserRepository' in your configuration.
You need to remove the #Profile(“jpa”) from UserRepository or you need to set "jpa" in "spring.profiles.default" property like:
spring.profiles.default=jpa
Issue is: you are creating UserRepository when profile is "jpa" but you haven’t add "jpa" to spring profiles. So spring have not created bean for UserRepository.

Bean of type Org.springframework.mail.javamail.JavaMailSender could not be found?

I just moved my project from Windows to Ubuntu. On Windows the program runs fine, but I get this error in Ubuntu:
Bean of type Org.springframework.mail.javamail.JavaMailSender could not be found
Below is the code and how i have used it . and it works on windows no using Ubuntu and getting this error
#Autowired
private JavaMailSender mailSender;
User user = userService.findByUsername(principal.getName());
Order order = orderService.createOrder(shoppingCart, shippingAddress, billingAddress, payment, shippingMethod, user);
mailSender.send(mailConstructor.constructOrderConfirmationEmail(user, order, Locale.ENGLISH));
shoppingCartService.clearShoppingCart(shoppingCart);
LocalDate today = LocalDate.now();
LocalDate estimatedDeliveryDate;
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mailSender in com.bookstore.controller.CheckoutController required a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found.
- Bean method 'mailSender' not loaded because AnyNestedCondition 0 matched 2 did not; NestedCondition on MailSenderAutoConfiguration.MailSenderCondition.JndiNameProperty #ConditionalOnProperty (spring.mail.jndi-name) did not find property 'jndi-name'; NestedCondition on MailSenderAutoConfiguration.MailSenderCondition.HostProperty #ConditionalOnProperty (spring.mail.host) did not find property 'host'
Action:
Consider revisiting the conditions above or defining a bean of type 'org.springframework.mail.javamail.JavaMailSender' in your configuration.
I think it has to do with anti virus , in windows i had to dis able anti virus but Ubuntu what do i do ?
Have you migrated your application.properties?
The bean is not loaded because of #ConditionalOnProperty annotation. It expect other beans/proprties to be initialized first which is governed by values in application.properties

Flyway and Spring Boot integration

I trying to integrate Flyway for migrations in a Spring Boot project with Hibernate and Spring JPA. I'm getting the following Exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Found non-empty schema "PUBLIC" without metadata table! Use init() or set initOnMigrate to true to initialize the metadata table.
My pom.xml is looking like this:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>3.2</version>
</dependency>
I'm using Hibernate and a config java file for postgres (dev stage) and h2 (local). The signatures are looking like this:
#Bean(initMethod = "migrate")
public Flyway flyway() {
Flyway fly = new Flyway();
fly.clean();
fly.init();
//flyway.setInitOnMigrate(true);
fly.setSchemas("SBA_DIALOG");
//flyway.setLocations("filesystem:src/main/resources/db/migration");
fly.setDataSource(this.dataSource());
fly.migrate();
return fly;
}
#Bean(name = "sbaEntityManagerFactory") #DependsOn("flyway")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
I can't find anything about my problem described in this question.
Can anybody help?
Spring-Boot is capable on it's own to do this.
Just add flyway as dependency to your project and spring-boot will pick it up.
Flyway migration will start when the service starts up.
If you already have some tables in the database add:
spring.flyway.baselineOnMigrate = true
in your property file to keep flyway calm when it discovers that some tables already exist. ;-)
Flyway should pick up your datasource. If you need for example another user or something like that for flyway, you can set these properties:
spring.flyway.url: jdbc:postgresql://${db.host}/${db.name}
spring.flyway.user: MYUSER
spring.flyway.password: MYPWD
(Of course add your values! You can use SPEL to reference other properties)
Update
One word of caution: If you use a clustered database you may encounter problems that multiple instances that are started at the same time try to perform the updates at the same time. This is a problem when the table locks don't work, which happened to me using a clustered mariaDB.
For any one who want to solve it in java code you can use :
fly.setBaselineOnMigrate(true);
Edit(22-09-2020)
another solution also is :
spring:
flyway:
baselineOnMigrate: true
validateOnMigrate: false

No bean named but bean is defined

I'm working on an update version of grail-oauth-plugin that support last spring-oauth
My plugin version works good and I have implemented a workin oauth2 server.
But now I want to add a custom-grant defined like this
def doWithSpring = {
myTokenGranter(MyTokenGranter)
xmlns oauth:"http://www.springframework.org/schema/security/oauth2"
oauth.'authorization-server'( /* ... many definitions here ... */){
/* ... many definitions here ... */
oauth.'custom-grant'('token-granter-ref': "myTokenGranter")
}
}
But I get an exception telling me:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTokenGranter'
But the bean myTokenGranter is defined as you can see. And If I remove the custom-grant definition the project starts and I can access the myTokenGranter bean.
Looking to a fullstack trace I see that the exception occur in the spring oatuh2 server bean definition parse AuthorizationServerBeanDefinitionParser.java in the line where it try to find my bean
parserContext.getRegistry().getBeanDefinition(customGranterRef);
where customGranterRef = "myTokenGranter"
so I suspect there is a bug in Spring Ouath or in Grails BeanBuilder that does not let my "myTokenGranter" to be visible in the server parser. Or making some error in grails bean definition DSL.
Thank you for your interest.
Debugging the app more deeply I have found that the problem probably is in how grails BeanBuilder work in translating namespaced spring DSL.
If I debug the point where my bean is checked (in AuthorizationServerBeanDefinitionParser.java)
at row
parserContext.getRegistry().getBeanDefinition(customGranterRef);
if I check che result of
parserContext.getRegistry().getBeanDefinitionNames()
it show me only this beans
[org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0
org.springframework.transaction.interceptor.TransactionInterceptor#0
org.springframework.transaction.config.internalTransactionAdvisor
oauth2TokenGranter
oauth2AuthorizationCodeServices
oauth2AuthorizationRequestManager]
And not all other decleared beans...
The problem exist even if I move the ouath server declaration inside resources.xml, keeping my custom token granter bean declaration inside resources.groovy.
But the problem solves if I move the custom token bean declaration inside resources.xml.
I don't really know how the BeanBuilder DSL works, but it seems like the problem is there if there is a problem (your example works just fine in XML). Can you do it in two steps, so the bean definition for myTokenGranter is definitely available when the OAuth2 namepsace is handled?
Solved hacking Spring Security Oauth
see this commit

Categories