I tried to follow this answer to add JDBC TokenStore to my app.
https://stackoverflow.com/a/37595818/148844
It is working with an InMemoryTokenStore. I need to know where to put this code
#Bean(name = "OAuth")
#ConfigurationProperties(prefix="datasource.oauth")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
I tried to put it in
#Configuration
#EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
But I got the error
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'OAuth2Configuration': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'OAuth': Requested bean is currently in creation: Is there an unresolvable circular reference?
So I moved it to the main class
#SpringBootApplication
#MapperScan("com.example.mapper")
public class ExampleApplication extends SpringBootServletInitializer {
But then it gave a different error
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: The url cannot be null
So where do I put that snippet to define the bean?
You need to have the database configuration properties in your application-{profile}.properties, in particular they need to be prefixed by datasource.oauth. Here profile will be any of the profiles that your application is running on (e.g: dev, stage, prod).
The error that is showing clearly says that there is no datasource.oauth.url=.. property in the specific properties file.
Related
I am using two Spring Entity manager, Arrango and JPA for my application.
#EnableSwagger2
#ComponentScan(basePackages = "com.xyz.abc")
#EnableArangoRepositories(basePackages = {"com.xyz.abc"})
#EnableJpaRepositories(basePackages = {"com.xyz.abc"})
#EntityScan(basePackages = "com.xyz.abc")
#SpringBootApplication
#EnableEurekaClient
#EnableDiscoveryClient
#EnableProcessApplication
As can be seen, I am Enabling repository access. Now when I run my application, I get the following error.
The bean 'XYZRepository', defined in com.xyz.abc.core.data.repository.XYZRepository defined in #EnableJpaRepositories declared on MYControllerAPP, could not be registered. A bean with that name has already been defined in com.xyz.abc.core.data.repository.XYZRepository defined in #EnableArangoRepositories declared on MyControllerAPP and overriding is disabled.
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
When I add overriding bean definition to my application.yml file.
The error changes to:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'qualityService': Unsatisfied dependency expressed through field 'master'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'masterDataRepository' defined in com.xyz.abc.core.data.repository.MasterDataRepository defined in #EnableJpaRepositories declared on QualityControllerApp: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.xyz.abc.core.data.model.MasterData
this is my MasterDataRepository Interface:
interface MasterDataRepository extends ArangoRepository<MasterData, String>
{
//Hibernate
}
I think the base problem with:
#EnableArangoRepositories(basePackages = {"com.xyz.abc"})
#EnableJpaRepositories(basePackages = {"com.xyz.abc"})
You should to set different packages to different repository providers. You won't be able to use one Entity class with different repositories. Try to separate ArangoRepository entities and JpaRepository entities.
I am trying to use the #Value annotation to grab the URI and database name while creating a SpringBootMongock object via SpringBootMongockBuilder and during mvn install it attempts to load the application context and fails because my Spring Contract tests cannot connect to the database in my application.yml file. Which I do not want while building my app anyways.
I have gotten around this by injecting the Environment object in my method signature but I don't understand why the #Value is not working. I have annotated the class with #Configuration which works fine.
Update: I still need to grab the URI from the yaml file to create my MongoClient using the #Bean annotation..
#Configuration
public class MongockConfiguration {
#Value(${spring.data.mongodb.uri})
private String uri;
#Bean
public MongoClient mongoClient(){
return MongoClients.create(uri);
}
#Bean
public SpringBootMongock mongock(Application context, Environment environment) throws Exception {
return new SpringBootMongockBuilder(mongoClient(), dbname, ChangeLogOne.class.getPackage().getName()).setEnabled(migrate).setApplicationContext(applicationContext).build();
}
some of the above values I pull from the Environment object as the #Value wasn't working for me .. no need to provide exact values here
exception is
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongock' defined in class path resource [blah/dht/mcs/registrationservice/config/MongockConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.github.cloudyrock.mongock.SpringBootMongock]: Factory method 'mongock' threw exception; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='testUser', source='admin', password=<hidden>, mechanismProperties={}}
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.github.cloudyrock.mongock.SpringBootMongock]: Factory method 'mongock' threw exception; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='testUser', source='admin', password=<hidden>, mechanismProperties={}}
Caused by: com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='testUser', source='admin', password=<hidden>, mechanismProperties={}}
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
and for the record with the values hardcoded vs using the #Value annotation everything works as expected.
The issue is not related to Mongock, but I see pretty clear that is due to MongoClient not being injected whenever you get the error.
As you mentioned it works when you provide the uri hardcoded, I was tempted to say that Spring doesn't find the spring.data.mongodb.uri, but if I am not wrong, it would fail saying that property is not found, rather than the error you are getting, as you are not providing a default value.
Anyway, it's something around there, for some reason, whenever you are running this and fails, the MongoClient is not added to the context for some reason.
I hope you find it useful.
I have the Spring Maven project using Java 11. Jboss WIldfly 15.0.1 Final is my deployment server.
To import data (objects using Hibernate) from one data source to another data source (MySQL)- I have added one primary entityManagerFactory with JpaTransactionManager and I have 2 other entity manager factories separate perisistenceUnits and a chainedTransactionManager being used(for 1 Phase commit-1PC commnit).
When deploying the war, sometimes, I get the below exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'someDAO': Injection of persistence dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'onetimeConfig': Injection of persistence dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityMgrFactory2' defined in class path resource [com/path/ImportConfig.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[javax.persistence.EntityManagerFactory]: Factory method 'entityMgrFactory2' threw exception;
nested exception is java.lang.IllegalStateException: 'url' not set
someDAO class header is:
#Transactional(rollbackFor = {Exception.class})
#Repository("someDAO")
public class SomeDAOImpl extends ParentDAOImpl implements SomeDAO {
The someDAO class extends the ParentDAOImpl class in which the primary entityManagerFactory is used and is also mentioned using #DependsOn. So, why does on deploy the creation of someDAO is trying to trigger the creation of entityMgrFactory2 when entityManagerFactory is mentioned in?!
#Repository("parentDAOImpl")
#DependsOn({"entityManagerFactory"})
public class ParentDAOImpl implements ParentDAO, Serializable {
#PersistenceContext
private transient EntityManager entityManager;
...
The problem never replicates on my local machine. It does occurs only while deploying on other servers and deployment fails due to this. And also the exception sometimes mentions someDAO and other times a different DAOclass that extends ParentDAOImpl.
Please help me, I am a novice.
We're trying to implement AspectJ #Aspect into our existing software for executing some code after a service call is made.
Note:
We have service interfaces and implementations being #Autowired
throughout the project via rest controllers as well as other service implementations.
This project is entirely a Java Configuration with no XML whatsoever.
We're using Spring 4.1.2 RELEASE deployed on Tomcat 7.0.54.
Issue:
When we added #EnableAspectJAutoProxy into our main #JavaConfig, we experience the following exception:
Unresolvable circular reference.
Which fails every #Autowired attempt on a long list of beans.
Tried:
Removed the #EnableAspectJAutoProxy annotation which autowires everything correctly but our #Aspect never gets invoked.
Added the CGLIB support in the annotation by declaring
proxytargetclass=true to no avail.
We've tried following this documentation directly from Spring: #EnableAspectJAutoProxy Javadoc
This seems to be an issue with AspectJ's proxy mechanism dealing with autowired dependencies.
Why does this occur when we add the #EnableAspectJAutoProxy?
Our Java Config:
#Configuration
#EnableWebMvc
#EnableJpaRepositories(basePackages ={"com.company.product.persistence.repository"})
#EnableTransactionManagement
#EnableSwagger
#EnableAspectJAutoProxy
#PropertySource({"classpath:hibernate.properties",
"classpath:auth.properties",
"classpath:mail.properties",
"classpath:locations.properties"
})
#ComponentScan(basePackages = {"com.company.product"})
public class WebConfig extends WebMvcConfigurerAdapter {
//Bean declarations here.
//Note: All services/repos/controllers are annotation based.
}
Aspect implementation:
#Aspect
#Component
public class PostMessageAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#After("execution(*com.company.product.persistence.serviceImpl.event.eventServiceImpl.methodCall(..))")
public void postMessageRun(final JoinPoint joinPoint) {
logger.info("CALLED AFTER METHOD");
}
}
Update:
Managed to get AOP/AspectJ working perfectly fine on one dev machine only requiring a minor change to our Spring Security config. We are both using Intellij, openJDK 1.7.0_65 on Ubuntu 14.0.4 running on default instances of Tomcat 7.0.56. On the other machine running the same software stack, gets the following.
Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingMessageController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.event.DispatchingEventService com.apx.efm.controllers.message.DispatchingMessageController.dispatchingEventService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingEventServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAd dressesService com.apx.efm.persistence.serviceImpl.event.DispatchingEventServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingAddressServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingService com.apx.efm.persistence.serviceImpl.building.BuildingAddressServiceImpl.buildingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAddressesService com.apx.efm.persistence.serviceImpl.building.BuildingServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.aopalliance.intercept.MethodInterceptor]: Factory method 'methodSecurityInterceptor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.apx.efm.persistence.service.user.EfmUserService com.apx.efm.application.config.SecurityConfig.efmUserService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'efmUserServiceImpl' defined in file [/home/apxdev4/Development/GitRepositories/efim-restful-web-service/target/EFIM/WEB-INF/classes/com/apx/efm/persistence/serviceImpl/user/EfmUserServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'methodSecurityInterceptor': Requested bean is currently in creation: Is there an unresolvable circular reference?
This was entirely an issue with our Spring configuration. Our Spring Security configuration was trying to #Autowired beans while they were still in the middle of being processed by our main application configuration. We solved this by ensuring that Spring Security gets configured after the main #Configuration.
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
// Initialize web mvc
appContext.setDisplayName("APP");
appContext.register(WebConfig.class);
appContext.register(SecurityConfig.class);
// Rest omitted (listeners, dispatcher servlet, etc.)
}
I have a Spring web application that is running just fine. I'm using JavaConfig, so there's not a lick of XML in the whole configuration. I'm trying to integrate Spring Security, but when I add a class that extends AbstractSecurityWebApplicationInitializer as directed by this tutorial, I get the following exception:
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:251)
...
Any idea how I can resolve this?
You probably need to ensure the security configuration is loaded. If the security configuration is not being loaded by other means, the AbstractSecurityWebApplicationInitializer should pass in the Security configuration to the super class as shown in the guide:
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
I was also having the same problem following the guide from the site.
Adding the code to the MessageSecurityWebApplicationInitializer.java solved the problem.
public MessageSecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
When I tried to add super(SecurityConfig.class) I get no default constructor found and I checked the class and there was a constructor with config parameter and no default, hence failed. Did anything change in 3.2.6?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.access.SecurityConfig]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.security.access.SecurityConfig.()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1093)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1038)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)