Error creating a bean webSecurityConfig through unsatisfied dependency field userDetailsService - spring-boot

I am working on a spring-boot, shopping-cart application.
Everything seems ok, the connection to mysql is working, JDBC is loaded, but i ll always get an exception, i can't find a solution on.
It seems that the Interface UserDetailsService is not properly working. I must say though that i use a deprecated hibernate method Query for Pagination Results. Could this be the reason? Help is appreciated after hours of search. I have no clue 😕Thanks....
Exception:
2018-03-19 18:44:23.192 WARN 10956 --- [main]
ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webSecurityConfig':
Unsatisfied dependency expressed through field 'userDetailsService';
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userDetailsService':
Unsatisfied dependency expressed through field 'accountDAO';
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'accountDAO':
Unsatisfied dependency expressed through field 'sessionFactory';
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory'
defined in com.maxmaxy.mangoshop.SpringBootMangoShopApplication:
Bean instantiation via factory method failed;
nested exception is
org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.hibernate.SessionFactory]:
Factory method 'getSessionFactory' threw exception;
nested exception is org.hibernate.MappingException:
Failed to scan classpath for unlisted classes
Pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
WebSecurityConfig:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.
AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.web.builders.
HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.
WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.
BCryptPasswordEncoder;
import com.maxmaxy.mangoshop.service.UserDetailsServiceImpl;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsServiceImpl userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws
Exception {
// Set service to find User in the database & set password encoder
BCryptPasswordEncoder bcryptPasswordEncoder = new
BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder
(bcryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
//Requires login with role EMPLOYEE or MANAGER. If not, will
redirect to /admin/login
http.authorizeRequests()
.antMatchers("/admin/orderList","/admin/order",
"/admin/accountInfo")
.access("hasAnyRole('ROLE_EMPLOYEE', 'ROLE_MANAGER'");
// Pages only for Manager
http.authorizeRequests().antMatchers("/admin/product")
.access("hasRole('ROLE_MANAGER')");
// When user login, role XX accessDeniedException
http.authorizeRequests().and().exceptionHandling()
.accessDeniedPage("/403");
//Configuration for login form
http.authorizeRequests().and().formLogin()
// Submit the Url
.loginProcessingUrl("/j_spring_security_check")
.loginPage("/admin/login")
.defaultSuccessUrl("/admin/accountInfo")
.failureUrl("/admin/login?error=true")
.usernameParameter("userName")
.passwordParameter("password")
// Configuration for the logout page
.and().logout().logoutUrl("/admin/logout")
.logoutSuccessUrl("/");
}
}
UserDetailsServiceImpl:
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority
.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails
.UserDetailsService;
import org.springframework.security.core.userdetails
.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.maxmaxy.mangoshop.dao.AccountDAO;
import com.maxmaxy.mangoshop.entity.Account;
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private AccountDAO accountDAO;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
Account account = accountDAO.findAccount(username);
System.out.println("Account= " + account);
if (account == null) {
throw new UsernameNotFoundException("User " //
+ username + " was not found in the database");
}
// EMPLOYEE,MANAGER,..
String role = account.getUserRole();
List<GrantedAuthority> grantList =
new ArrayList<GrantedAuthority>();
// ROLE_EMPLOYEE, ROLE_MANAGER
GrantedAuthority authority = new SimpleGrantedAuthority(role);
grantList.add(authority);
boolean enabled = account.isActive();
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
UserDetails userDetails = (UserDetails) new
User(account.getUserName(), //
account.getEncryptedPassword(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, grantList);
return userDetails;
}
}
And the last mentioned class in the exception, AccountDAO:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.maxmaxy.mangoshop.entity.Account;
#Transactional
#Repository
public class AccountDAO {
#Autowired
private SessionFactory sessionFactory;
public Account findAccount(String userName) {
Session session = this.sessionFactory.getCurrentSession();
return session.find(Account.class, userName);
}
}

I think it's more easier with spring data you already load it with maven and this is a good step, now you should use it.
don't creat you repository based on session factory but based on spring data like this.
#Repository public interface AccountRepository extends
JpaRepository<AccountEntity, String> {
AccountEntity findByEmail(String username);
AccountEntity findByName(String name);
}
now you can #Autowired it where you want (you don't need any implementations, he understand that AccountEntity is the entity and it have Email and name as an attribute and you need to search by them ^^ )
its well documented if you need any other future

Related

hibernate ClassCastException with mvn spring-boot:run

when I start the server using the jar:
java -jar core-0.0.1-SNAPSHOT.jar
then everything works fine.
But when i use the maven plugin:
mvn spring-boot:run
then i get the following error message:
2020-09-28 23:09:46.633 DEBUG 13970 --- [ main] d.j.p.server.core.ServerApplication : Running with Spring Boot v2.1.6.RELEASE, Spring v5.1.8.RELEASE
2020-09-28 23:09:46.634 INFO 13970 --- [ main] d.j.p.server.core.ServerApplication : No active profile set, falling back to default profiles: default
2020-09-28 23:09:49.120 ERROR 13970 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message:
Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]:
Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseTransactionManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]:
Factory method 'baseTransactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'baseEntityManager' defined in class path resource [de/jwt/project/server/core/config/BaseDataSourceConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]:
Factory method 'baseEntityManager' threw exception; nested exception is java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType
(java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
2020-09-28 23:09:49.167 WARN 13970 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2020-09-28 23:09:49.188 ERROR 13970 --- [ main] o.s.boot.SpringApplication : Application run failed
Unfortunately I have no idea what the cause can be,
i am grateful for every help
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>de.jwt.project.server</groupId>
<artifactId>core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Server</name>
<description>Server</description>
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
<project.reporting.outputEncoding>ISO-8859-1</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<!--<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>-->
<repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-bom</artifactId>
<version>Bean-SR3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<!-- send email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>de.jwt.project.remoteservice</groupId>
<artifactId>de.jwt.project.remoteservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/net.imagej/ij -->
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.52i</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--
<dependency>
<groupId>de.agital.project.caritas</groupId>
<artifactId>de.agital.project.caritas</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>-->
<dependency>
<groupId>org.wickedsource.docx-stamper</groupId>
<artifactId>docx-stamper</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
#SpringbootApplication main class
package de.jwt.project.server.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.naming.NoPermissionException;
import javax.servlet.Filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import de.jwt.project.database.components.ModelResource;
import de.jwt.project.database.components.Referenz;
import de.jwt.project.database.tenant.Account;
import de.jwt.project.database.tenant.Geschaeftspartner;
import de.jwt.project.database.tenant.GespeicherteAbfrage;
import de.jwt.project.database.tenant.Instanz;
import de.jwt.project.database.tenant.Instanzwert;
import de.jwt.project.database.tenant.Rolle;
import de.jwt.project.database.tenant.Team;
import de.jwt.project.database.tenant.Vertrag;
import de.jwt.project.database.tenant.VertragInstanzBez;
import de.jwt.project.database.types.OperationsForQuery;
import de.jwt.project.remoteservice.components.ReferenzHierachy;
import de.jwt.project.server.core.dao.tenant.AccountDao;
import de.jwt.project.server.core.dao.tenant.RolleDao;
import de.jwt.project.server.core.migration.MetadataGenerator;
import de.jwt.project.server.core.multitenant.MultiTenantFilter;
import de.jwt.project.server.core.service.AccountService;
import de.jwt.project.server.core.service.ResourceService;
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
#SuppressWarnings("unused")
public class ServerApplication {
private static Account login(final ConfigurableApplicationContext context, String username, String password,
String tenant) {
final AccountDao accountDao = context.getBean(AccountDao.class);
final RolleDao rolleDao = context.getBean(RolleDao.class);
final AccountService accountService = context.getBean(AccountService.class);
final MetadataGenerator metaGen = context.getBean(MetadataGenerator.class);
Account admin = null;
try {
admin = (Account) accountService.loadUserByUsername(username);
} catch (UsernameNotFoundException e) {
e.printStackTrace();
}
if (admin == null) {
admin = new Account();
admin.setUsername(username);
admin.setPassword(password);
Rolle rolle = rolleDao.findByDescription("Administrator");
if (rolle == null) {
rolle = new Rolle();
rolle.setDescription("Administrator");
rolle = rolleDao.save(rolle);
}
Set<Rolle> rollen = new HashSet();
rollen.add(rolle);
admin = accountService.save(admin);
admin.setRoles(rollen);
admin = accountService.save(admin);
}
metaGen.execute(admin, "metadaten_caritas.xml");
return admin;
}
private static void encryptPW(final ConfigurableApplicationContext context) {
final BCryptPasswordEncoder enc = new BCryptPasswordEncoder();
final AccountDao accountDao = context.getBean(AccountDao.class);
// -------------------------------
final List<Account> lstAccount = accountDao.findAll();
for (final Account account : lstAccount) {
if (!account.isEncrypted()) {
account.setPassword(enc.encode(account.getPassword()));
account.setEncrypted(true);
accountDao.save(account);
}
}
}
public static void main(final String[] args) throws Throwable {
final ConfigurableApplicationContext context = SpringApplication.run(ServerApplication.class, args);
Properties properties = new Properties();
try (InputStream inputStream = ServerApplication.class.getClassLoader().getResourceAsStream("application.properties")) {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
String username = properties.getProperty("backenduser");
String pw = properties.getProperty("backenduserpassword");
Account account = login(context, username, pw, "carritas_db");
// Verschlüssele Passwörter im Klartext
encryptPW(context);
//createAuskunftverlangen(context, account);
}
private static void createAuskunftverlangen(ConfigurableApplicationContext context, Account account) {
final ResourceService ressourceService = context.getBean(ResourceService.class);
try {
GespeicherteAbfrage abfrage = (GespeicherteAbfrage) ressourceService
.getByDescription(GespeicherteAbfrage.class, "Auskunftsverlangen");
if (abfrage != null) {
return;
}
ReferenzHierachy hierachy = new ReferenzHierachy(Instanzwert.class, true);
hierachy.addJoin(Instanz.class, "instanz", "id", "instanz", null);
hierachy.addJoin(VertragInstanzBez.class, "id", "instanz", "vib", "instanz");
hierachy.addJoin(Vertrag.class, "vertrag", "id", "vertrag", "vib");
hierachy.addCondition(hierachy.createFilter(Referenz.class, "geschaeftspartner", OperationsForQuery.EQUALS,
new Geschaeftspartner().toReferenz(), "instanz"));
hierachy.addAdditionalField(String.class, "wert", null, "gespeicherter Wert");
hierachy.addAdditionalField(ModelResource.class, "referenz", null, "gespeicherte Referenz");
hierachy.addAdditionalField(String.class, "vertragsnummer", "vertrag", "Vertragsnummer");
hierachy.addAdditionalField(String.class, "description", "vertrag", "Vertrag");
Team team = new Team(account);
abfrage = new GespeicherteAbfrage();
abfrage.setBesitzer(team.toReferenz());
abfrage.setDescription("Auskunftsverlangen");
abfrage.setAbfrage(hierachy.serialize());
abfrage = (GespeicherteAbfrage) ressourceService.save(abfrage);
} catch (IOException | NoPermissionException | ClassNotFoundException e) {
e.printStackTrace();
return;
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean someFilterRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(someFilter());
registration.addUrlPatterns("/api/auth/login/*");
registration.setName("MultiTenantFilter");
registration.setOrder(1);
return registration;
}
public Filter someFilter() {
return new MultiTenantFilter();
}
}
BaseDataSourceConfig:
package de.jwt.project.server.core.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#EnableJpaRepositories(
basePackages = "de.jwt.project.server.core.dao.base",
entityManagerFactoryRef = "baseEntityManager",
transactionManagerRef = "baseTransactionManager"
)
public class BaseDataSourceConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean baseEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("persistence.base");
em.setDataSource(baseDataSource());
em.setPackagesToScan("de.jwt.project.database.base", "de.jwt.project.database.components");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.afterPropertiesSet();
return em;
}
#Primary
#Bean
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource baseDataSource() {
DataSource ds = DataSourceBuilder.create()
.build();
return ds;
}
#Primary
#Bean
public PlatformTransactionManager baseTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
baseEntityManager().getObject());
return transactionManager;
}
}
The image shows the point where the exception is thrown.
The cast exception is thrown in the AttributeConverterDefinition.resolveType() method.
And her the code from the ReferenzConverter.class.
This is the class which cause the cast exception.
package de.jwt.project.database.components;
import java.util.UUID;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter(
autoApply = true
)
public class ReferenzConverter<T extends ModelResource> implements AttributeConverter<Referenz<T>, UUID> {
public ReferenzConverter() {
}
public UUID convertToDatabaseColumn(Referenz<T> attribute) {
return attribute == null ? null : attribute.getId();
}
public Referenz<T> convertToEntityAttribute(UUID dbData) {
if (dbData == null) {
return null;
} else {
Referenz ref = new Referenz(dbData);
return ref;
}
}
}
.....................................................

Error creating spring boot bean - "The blank final field em may not have been initialized"

I am a newbie for the spring boot framework. I have successfully done crud operation. After that I have decided that to do Advanced search concepts. Please see the code below, which I used.
package com.lean.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.repository.JpaRepository;
import com.lean.entity.Merchant;
public interface MerchantDao extends JpaRepository<Merchant, Long> {
EntityManager em;
public List<Merchant> findAllByNameIn(Set<String> name);
public default List<Merchant> findMerchantList(String name, String email) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Merchant> cq = cb.createQuery(Merchant.class);
Root<Merchant> book = cq.from(Merchant.class);
List<Predicate> predicates = new ArrayList<>();
if (name != null) {
predicates.add(cb.equal(book.get("name"), name));
}
if (email != null) {
predicates.add(cb.equal(book.get("email"), email));
}
cq.where(predicates.toArray(new Predicate[0]));
return em.createQuery(cq).getResultList();
};
}
Here, I am getting the below error.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'merchantDao': Invocation of init method failed; nested exception is java.lang.Error: Unresolved compilation problem:
The blank final field em may not have been initialized
When I am trying to get the"EntityManager em" entity object, I will get the above error.
Please help someone to fix the issue. Thanks in advance
Try this :-
#PersistenceContext
private EntityManager em;
Also check for below dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>

I deploye spring boot api in tomcat 8 nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException

I deployed spring boot api in tomcat8 it is not working but my in embedded tomcat it works can any one help me to solve this
this is the error
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUserRepository': Cannot create inner bean '(inner bean)#59552bd4' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#59552bd4': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitiali
this is my webSecurityConfig file
package com.grokonez.jwtauthentication.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.grokonez.jwtauthentication.security.jwt.JwtAuthEntryPoint;
import com.grokonez.jwtauthentication.security.jwt.JwtAuthTokenFilter;
import com.grokonez.jwtauthentication.security.services.UserDetailsServiceImpl;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(
prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsServiceImpl userDetailsService;
#Autowired
private JwtAuthEntryPoint unauthorizedHandler;
#Bean
public JwtAuthTokenFilter authenticationJwtTokenFilter() {
return new JwtAuthTokenFilter();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.grokonez.jwtauthentication</groupId>
<artifactId>SpringBootJwtAuthentication</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>SpringBootJwtAuthentication</name>
<description>SpringBootJwtAuthentication</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- For Working with Json Web Tokens (JWT) -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
i tried it in tomcat 9 and 8 but not working how can i solve this problem and i am using token based authentication this is a spring boot api and i am using #Autowired
Have you tried to understand your exception? It clearly explains the bean creation flow for your particular config and this seems the root:
nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Make sure you have required jar for JAXB in class path, you can print class path using --debug option or extract jar and confirm.

UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'

I am trying to connect backend and frontend two separate projects of eclipse spring maven. I have added dependency to do so. But when I write down validate credentials logic in Homecontroller.java, after running on server its showing this exception. Please help to resolve it I have tried many methods already please suggest.
HomeController.java
package com.yogesh.shoponlinefrontend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Controller
public class HomeController {
#Autowired
UserDAO userDAO;
#RequestMapping("/")
public String homePage() {
System.out.println("Executing the method homePage");
return "home";
}
#RequestMapping("/login")
public ModelAndView showLoginPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked login link");
mv.addObject("showLoginPage", "true");
return mv;
}
#RequestMapping("/register")
public ModelAndView showRegistrationPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked Registration link ");
mv.addObject("showRegistrationPage", "true");
return mv;
}
#RequestMapping("/validate")
public ModelAndView validate(#RequestParam("id") String id, #RequestParam("password") String pwd) {
System.out.println("In validate method");
System.out.println("id: " + id);
System.out.println("pwd: " + pwd);
ModelAndView mv = new ModelAndView("home");
if (userDAO.validate(id, pwd) != null) {
mv.addObject("successMsg", "You logged in successfully");
} else {
mv.addObject("errorMsg", "Invalid Credentials..Please try again");
}
return mv;
}
}
UserDAO.java
package com.yogesh.shoponlineback.dao;
import java.util.List;
import com.yogesh.shoponlineback.model.User;
public interface UserDAO {
public List<User> list();
public User get(String username);
public User validate(String username, String password);
public boolean save(User user);
public boolean update(User user);
}
User.java
package com.yogesh.shoponlineback.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Entity
//cha
#Table(name="USER")
#Component
public class User {
#Id
private String username;
#NotEmpty(message = "please enter your name")
private String name;
#Min(5)
#Max(15)
private String password;
private String mobile;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserDAOImpl.java
package com.yogesh.shoponlineback.daoimpl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Service
#Repository()
public class UserDAOImpl implements UserDAO {
#Autowired
UserDAO userDAO;
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public UserDAOImpl() {
// TODO Auto-generated constructor stub
}
#Transactional
public List<User> list() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
#Transactional
public User get(String username) {
return (User) sessionFactory.getCurrentSession().get(User.class, username);
}
#Transactional
public User validate(String username, String password) {
String hql = "from User WHERE username ='" + username + "' and password='" + password + "'";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return (User)query.uniqueResult();
}
#Transactional
public boolean save(User user) {
try {
sessionFactory.getCurrentSession().save(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Transactional
public boolean update(User user) {
try {
sessionFactory.getCurrentSession().update(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
:::::::::::::::::::::::::::::Exception trace::::::::::::::::::::::::::::::::::
INFO: FrameworkServlet 'dispatcher': initialization started
Jan 10, 2017 3:19:22 PM **org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Jan 10 15:19:22 IST 2017]; root of context hierarchy
Jan 10, 2017 3:19:22 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.yogesh.shoponlinefrontend.config.AppConfig]
Jan 10, 2017 3:19:23 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Jan 10, 2017 3:19:23 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Jan 10, 2017 3:19:23 PM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at `enter code here`org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at** org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
I have updated to this:
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend,com.yogesh.shoponlineback")
from
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend)
and it's now working fine.
I had the same problem! My POM file was configured incorrectly.
Check your dependencies (versions).
THis configuration works for me.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stoliarenko</groupId>
<artifactId>CustomerTracker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- <version>1.0-SNAPSHOT</version>-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring.version>5.1.0.RELEASE</spring.version>
<hibernate.version>5.3.5.Final</hibernate.version>
<hibernate.validator>5.4.1.Final</hibernate.validator>
<c3p0.version>0.9.5.2</c3p0.version>
<jstl.version>1.2.1</jstl.version>
<tld.version>1.1.2</tld.version>
<servlets.version>3.1.0</servlets.version>
<jsp.version>2.3.1</jsp.version>
<hsqldb.version>1.8.0.10</hsqldb.version>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator}</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${tld.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlets.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>

spring-boot, spring-boot-starter-data-jpa: database type NONE or Cannot find changelog location

me again, now with a spring-boot-starter-data-jpa Problem. I using spring-boot to access multiple databases. MongoDB went right, also Cassandra, last one PostgreSQL and JPA have some problems. i think my configuration may be wrong. Could you help me to figure it out? I used the spring-boot, spring-data-jpa reference and spring-boot-starter-data-jpa reference. Nothing helped. I found some threads at stakeoverflow, that use jdbc with hsql dependency because jpa won't function correctly Link. I tried this myself but than i get a no qualifying bean error.
So i did a step back, included jpa and hsql, write a PostgresConfig class nothing helped. If i use the #EnableJpaRepositories Annotation i get a wired Error. See Stacktrace Para 67.5.2 Error... I didn't use this liquibase thingy, idk why there is an error... Otherwise if i won't use DataSourceBuilder my application.properties won't be read and i got the database type NONE error.
Some Source:
Stack Trace:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at com.kage.bigdata.bida.Application.main(Application.java:22)
Caused by: java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.util.Assert.state(Assert.java:385)
at org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration.checkChangelogExists(LiquibaseAutoConfiguration.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
... 26 more
application.properties:
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.schema=bigdata
spring.datasource.platform=postgresql
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.database=postgresql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=drop-create
Config:
package com.kage.bigdata.bida.config;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
*
* #author bl4ckbird
*/
#Configuration
#EnableJpaRepositories("com.kage.bigdata.bida.repository.postgres")
public class PostgresConfig {
#Bean
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
}
POM.XML:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kage.bigdata</groupId>
<artifactId>bida</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Application:
package com.kage.bigdata.bida;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* #author bl4ckbird
*/
#SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}
Repository:
package com.kage.bigdata.bida.repository.postgres;
import com.kage.bigdata.bida.model.Question;
import org.springframework.data.jpa.repository.JpaRepository;
/**
*
* #author bl4ckbird
*/
public interface QPostgresRepository extends JpaRepository<Question, String> {
}
QuestionEntity (multi-annotated(cassandra,mongo,jpa):
package com.kage.bigdata.bida.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
/**
*
* #author bl4ckbird
*/
#Table
#Entity
public class Question implements Serializable{
#Id
#PrimaryKey
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.AUTO)
#javax.persistence.Id
private String id;
#Getter
#Setter
private String question;
#Override
public String toString() {
return String.format(
"Question[id=%s, Question='%s']",
id, question);
}
}
Autowired Service:
package com.kage.bigdata.bida.service.impl;
import com.kage.bigdata.bida.model.Question;
import com.kage.bigdata.bida.repository.cassandra.QCassandraRepository;
import com.kage.bigdata.bida.repository.QuestionRepository;
import com.kage.bigdata.bida.repository.postgres.QPostgresRepository;
import com.kage.bigdata.bida.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author bl4ckbird
*/
#Service
public class QuestionServiceImpl implements QuestionService{
#Autowired
QuestionRepository questionRepository;
#Autowired
QCassandraRepository cassandraRepository;
#Autowired
QPostgresRepository postgresRepository;
public QuestionServiceImpl(){};
#Override
#Transactional
public void test() {
Question q = new Question();
q.setQuestion("Frage");
questionRepository.save(q);
System.out.println(questionRepository.findAll());
q.setQuestion("Frage2");
cassandraRepository.save(q);
System.out.println(cassandraRepository.findAll());
}
}
GOT IT WORKING! Finally... What i did: delete HSQLDB from pom deb. Put liquidbaseautoconfiguration.class to exclude... 1 line of Code and 8 hours code reading.. here my Configuration Class. Hope i could help somebody:
#Configuration
#EnableAutoConfiguration(exclude =
LiquibaseAutoConfiguration.class
)
#EnableJpaRepositories("com.kage.bigdata.bida.repository.postgres")
public class PostgresConfig {
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/postgres");
dataSource.setUsername("postgres");
dataSource.setPassword("postgres");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("com.kage.bigdata.bida.model");
entityManagerFactoryBean.setJpaProperties(buildHibernateProperties());
entityManagerFactoryBean.setJpaProperties(new Properties() {{
put("hibernate.current_session_context_class", SpringSessionContext.class.getName());
}});
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter() {{
setDatabase(Database.POSTGRESQL);
}});
return entityManagerFactoryBean;
}
protected Properties buildHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.use_sql_comments", "false");
hibernateProperties.setProperty("hibernate.format_sql", "false");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty("hibernate.generate_statistics", "false");
hibernateProperties.setProperty("javax.persistence.validation.mode", "none");
//Audit History flags
hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", "true");
hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", "true");
return hibernateProperties;
}
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
#Bean
public TransactionTemplate transactionTemplate() {
return new TransactionTemplate(transactionManager());
}
}
You must exclude liquibase from the string-data-cassandra dependency like so :
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.2.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</exclusion>
</exclusions>
</dependency>

Resources