My project use spring boot 1.3.8 and now I have to upgrade hibernate from 4.* to 5.*. When I add dependencies and start project I have error "java.lang.AbstractMethodError" after initialization Datasource bean. What can I do for resolve this problem ?
#Bean
public LocalContainerEntityManagerFactoryBean ussdDBEntityManagerFactory(final EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean emf = builder
.dataSource(ussdDBDataSource())
.persistenceUnit("ussdDBPersistenceUnit")
.build();
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "none");
emf.setJpaProperties(properties);
return emf;
}
Error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ussdDBEntityManagerFactory' defined in class path resource [com/intech/kievstar/config/DBUssdConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
Solution of my problem was dependency:
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>5.0.0.GA</version>
</dependency>
When I up verson to 5.0.0.GA, problem was resolved
Related
My spring boot test is throwing the below error during maven build.
"level":"ERROR","logger":"com.zaxxer.hikari.HikariConfig","msg":"HikariPool-1 - jdbcUrl is required with driverClassName."
Stacktrace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource
[com/pit/SchedulerConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is requir
ed with driverClassName.
Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
The method that throws an error in my MyApplicationTest.java
#SpringBootTest
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableConfigurationProperties(value = MyConfig.class)
class MyApplicationTest {
#Test
void contextLoads() {
assertNotNull(myController);
}
}
My pom has these dependencies in classpath.
spring-boot-starter-web
spring-boot-starter-test
spring-integration-sftp
postgresql
junit
quartz-scheduler
My Datasource bean is configured as below
#Configuration
public class MyDataSourceCfg {
private DataSource appDataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url(env.getProperty("url") // values are set from Environment
.username(env.getProperty("user"))
.password(env.getProperty("password")
.build();
}
}
Please tell me what is happening and how I avoid this error. I read about configuring Datasource in different way in case you have multiple database but I just have one postgres database. Please share your thoughts.
Considering that you have all relevant dependencies.
as Connect to PostgreSQL Database with Spring Data JPA such as :-
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and in application.properties file:
spring.datasource.url=jdbc:postgresql://localhost:5432/dev
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
With SpringBoot's powerful autoconfiguration, you don't need to explicitly create a DataSource bean and if in case you want, use these properties values.
I have upgraded springfox to version 2.7.0(and 2.9.2):
<springfox.version>2.7.0</springfox.version>
<spring-boot.version>1.3.3.RELEASE</spring-boot.version>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>${springfox.version}</version>
</dependency>
and trying to start the application I get the next error:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'documentationPluginsBootstrapper'
defined in URL
[jar:file:.....jar!/lib/springfox-spring-web-2.7.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]:
Unsatisfied dependency expressed through constructor argument with
index 1 of type [java.util.List]: Error creating bean with name
'basePathAwareServicesProvider' defined in URL
[jar:file:/..............!/lib/springfox-data-rest-2.7.0.jar!/springfox/documentation/spring/data/rest/BasePathAwareServicesProvider.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[springfox.documentation.spring.data.rest.BasePathAwareServicesProvider]:
No default constructor found; nested exception is
java.lang.NoSuchMethodException:
springfox.documentation.spring.data.rest.BasePathAwareServicesProvider.();
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'basePathAwareServicesProvider' defined in URL
[jar:file:............!/lib/springfox-data-rest-2.7.0.jar!/springfox/documentation/spring/data/rest/BasePathAwareServicesProvider.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[springfox.documentation.spring.data.rest.BasePathAwareServicesProvider]:
No default constructor found; nested exception is
java.lang.NoSuchMethodException:
springfox.documentation.spring.data.rest.
BasePathAwareServicesProvider. init ()
No default constructor found; BasePathAwareServicesProvider. init ()
I have annotated the classes like this in order to avoid some errors with swaggers-ui.html:
#Configuration
#Profile("swaggerEnabled")
#EnableSwagger2
#EnableWebMvc
#Import(SpringDataRestConfiguration.class)
public class SwaggerConfiguration {
The Springboot application:
#EnableSwagger2
#EnableWebMvc
#SpringBootApplication
#Import(value = {
......class,})
#Order(Ordered.HIGHEST_PRECEDENCE)
#ComponentScan(basePackages = {"....."})
public class PlatformApiApplication {
I've tried some solutions from github but nothing works. Can somebody help me? thanks.
Removing the line:
#Import(SpringDataRestConfiguration.class)
The error dissapears
While trying to follow the article https://sandor-nemeth.github.io/java/spring/2017/06/15/spring-boot-with-keycloak.html
I set up my keycloak oauth in spring boot application exactly the same apart form the fact that I am using maven pom.xml instead of gradle.
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-2-starter</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-adapter</artifactId>
<version>9.0.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>9.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
The Java part is the same as in the article:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class KeycloakSecurityConfigurer extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) {
final SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
mapper.setConvertToUpperCase(true);
final KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
provider.setGrantedAuthoritiesMapper(mapper);
auth.authenticationProvider(provider);
}
#Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests();
}
While trying to start the spring boot application
java ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom -jar "${HOME}/app.war" "$#"
I am getting BeanInCreationException:
rg.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.keycloak.adapters.springboot.KeycloakAutoConfiguration': Unsatisfied dependency expressed through method 'setKeycloakSpringBootProperties' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'keycloakSecurityConfigurer': Unsatisfied dependency expressed through field 'keycloakConfigResolver'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'keycloakConfigResolver': Requested bean is currently in creation: Is there an unresolvable circular reference?","logger":"org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext","thread":"main","level":"WARN"}
{"time":"2020-03-10T12:53:22.667+00:00","msg":"Application run failed","logger":"org.springframework.boot.SpringApplication","thread":"main","level":"ERROR","stack_trace":"org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.keycloak.adapters.springboot.KeycloakAutoConfiguration': Unsatisfied dependency expressed through method 'setKeycloakSpringBootProperties' parameter 1
I created a spring JPA example according to "Spring in Action", chapter 11.
Java config code:
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
System.out.println(adapter);
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return adapter;
}
#Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
//emfb.setPersistenceUnitName("test");
emfb.setJpaVendorAdapter(jpaVendorAdapter);
emfb.setPackagesToScan("com.springinaction.test");
EntityManagerFactory emf = emfb.getObject();
System.out.println(emf);
return emf;
}
#Bean
public PlatformTransactionManager annotationDrivenTransactionManager(EntityManagerFactory emf) {
//System.out.println(emf);
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Maven dependencies associated with Spring JPA:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
The program runs fine up to this line of code:
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
and fails with below error message:
hello
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class com.springinaction.test.JdbcConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.JpaVendorAdapter com.springinaction.test.JdbcConfig.jpaVendorAdapter()] threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
Someone said to me that the reason could be the absence of hibernate-entitymanger.jar, but I find this jar in local Maven repository.
And someone says that reason is missing ejb3-persistence.jar, but I couldn't find the Maven groupId/artifactId for this.
Can someone please explain this to me?
Class org.hibernate.ejb.HibernatePersistence is part of hibernate-entitymanager jar. Please check if this jar is in your project class path or in deployed war file. Also check the version of this jar file.Instead of providing hibernate-core and hibernate-jpa you should provide hibernate-entitymanager dependency in pom.xml and this will download all the required dependencies. You can check the same at https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager/5.2.2.Final
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
The source code for Spring In Action is at https://manning-content.s3.amazonaws.com/download/9/ef4e0ef-b7bd-4ab8-857d-eb635d18d425/SpringiA4_SourceCode.zip. You can check the build.gradle file for dependency used.
I'd like to make use of spring-data-jpa and CrudRepository<T, ID extends Serializable>. But I cannot get it autowired. (all other services in the same package are wired correctly):
#Service
public class UserService {
#Resource
private UserRepo repo;
//this does neither work
//#Autowired
//private CrudRepository<User, Long> repo;
}
public interface UserRepo extends CrudRepository<User, Long> {
}
#Entity
public class User {
#Id
private Long id;
}
Result:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userService': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [UserRepo] found for dependency: expected at
least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations:
{#javax.annotation.Resource(shareable=true, mappedName=, description=,
name=, type=class java.lang.Object, lookup=,
authenticationType=CONTAINER)}
What might be wrong here?
From the docs I think it should work without writing an implementation:
In a typical Java application, you’d expect to write a class that
implements CustomerRepository. But that’s what makes Spring Data JPA
so powerful: You don’t have to write an implementation of the
repository interface. Spring Data JPA creates an implementation on the
fly when you run the application.
Updated SpringConfig:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("my.package")
public class AppConfig {
#Bean
public LocalContainerEntityManagerFactoryBean emf() throws ClassNotFoundException, PropertyVetoException {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("my.package");
emf.setJpaVendorAdapter(jpaAdapter());
emf.setJpaProperties(jpaProterties());
return emf;
}
}
Result: emf is missing, which is strange as I already have working DAO serices where I can autowire EntityManager and EMF without any problem.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1a6e658': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:632)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:442)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
... 50 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 58 more
You should verify the following:
1) Annotate the UserRepo with #Repository.
2) Your spring beans xml file should have in it:
<jpa:repositories base-package="your.repository.package"></jpa:repositories>
3) I'd recommend injecting this type of bean with #Autowired instead of #Resource
UPDATE
it seems you did my first 3 steps and you're one step ahead now. Now, remember that in Java Config methods names DO matter. Either change emf() to entityManagerFactory() (which is more "standard"), or set entity-manager-factory-ref to emf. Example:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException, PropertyVetoException {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("my.package");
emf.setJpaVendorAdapter(jpaAdapter());
emf.setJpaProperties(jpaProterties());
return emf;
}
Doesn't UserRepo needs to be annotated with :
#Repository
It must be an issue in your applicationContext configuration. Here is the one I used to made it work:
<jpa:repositories
base-package="package.containing.your.repositories"
factory-class="org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean
id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:persistenceUnitName="PU"
p:jpaVendorAdapter-ref="hibernateJpaVendorAdapter"
p:jpaProperties="classpath:hibernate.properties" />
<util:property-path id="sessionFactory" path="entityManagerFactory.sessionFactory" />
Configuring spring data JPA using XML and annotations
//This is the two way to configure spring data JPA
#EnableJpaRepositories (basePackages= "Repository Bean is located in package", entityManagerFactoryRef= "Here is your configuration of EntityManagerFactoryBean")
<jpa:repositories base-package= "Repository Bean where package"
Entity-manager-factory-ref= "Here is your configured EntityManagerFactoryBean" ></jpa:repositories>
// Sample code:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.zxg.springdata",
entityManagerFactoryRef="factoryBean")
public class SpringDataConfig {
#Bean
public LocalContainerEntityManagerFactoryBean factoryBean (
ComboPooledDataSource dataSource, JpaVendorAdapter jpaVendorAdapter
){
LocalContainerEntityManagerFactoryBean factoryBean = new
LocalContainerEntityManagerFactoryBean ();
FactoryBean.setDataSource (dataSource);
FactoryBean.setJpaVendorAdapter (jpaVendorAdapter);
FactoryBean.setPackagesToScan ("com.zxg.springdata");
Return factoryBean;
}
}