I’m building an monolith spring project. I work with spring 3.4.0, java 17, jwt version 0.12.6.
I just design and set up entities and jwt infrastructures and I got this issue. Many times I looked for a wrong definition. I never figured out it.
that is full of error string
Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'jwtAuthenticationFilter' defined in file [C:UsersmrzcnDesktopecommerceecommerce-backendtargetclassescomexampleecommercesecurityJwtAuthenticationFilter.class]: Unsatisfied dependency expressed through constructor parameter 1: Error creating bean with name 'customUserDetailsService' defined in file [C:UsersmrzcnDesktopecommerceecommerce-backendtargetclassescomexampleecommercesecurityCustomUserDetailsService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'userRepository' defined in com.example.ecommerce.repository.UserRepository defined in @EnableJpaRepositories declared on EcommerceApplication: Cannot resolve reference to bean 'jpaSharedEM_entityManagerFactory' while setting bean property 'entityManager'
and bellow files about error.
<?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 https://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>3.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ecommerce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ecommerce</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
<jwt.version>0.12.6</jwt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-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.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
that is my User entity
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, length = 100, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@OneToOne
@JoinColumn(name = "customer_id")
private Customer customer;
@Enumerated(EnumType.STRING)
private AccountStatus accountStatus;
@OneToOne
@JoinColumn(name = "cart_id")
private Cart cart;
@Column(nullable = false, length = 15)
private String phoneNumber;
@Enumerated(EnumType.STRING)
private Role role;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime registerDate;
private LocalDateTime deletedDate;
@Column(nullable = false, columnDefinition = "boolean default false")
private boolean isMailVerified = false;
@Column(nullable = false, columnDefinition = "boolean default false")
private boolean isPhoneNumberVerified = false;
@Column(nullable = false, columnDefinition = "boolean default false")
private boolean isSmsAvailable = false;
@Column(nullable = false, columnDefinition = "boolean default false")
private boolean isEmailAvailable = false;
@Column(nullable = false, columnDefinition = "boolean default false")
private boolean isPushNotificationAvailable = false;
@OneToMany(mappedBy = "user" ,fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<UserActionLog> userActionLogs;
@OneToMany(mappedBy = "user" ,fetch = FetchType.LAZY)
private List<Wishlist> wishlists;
@OneToMany(mappedBy = "user" ,fetch = FetchType.LAZY)
private List<Notification> notifications;
JwtAuthenticationFilter
package com.example.ecommerce.security;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.context.SecurityContextHolder;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter{
private final JwtService jwtService;
@Autowired
private final CustomUserDetailsService customUserDetailsService;
public JwtAuthenticationFilter(JwtService jwtService, CustomUserDetailsService customUserDetailsService) {
this.jwtService = jwtService;
this.customUserDetailsService = customUserDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String token = getTokenFromHeader(request);
if(token != null && SecurityContextHolder.getContext().getAuthentication() == null){
String username = jwtService.extractUser(token);
if(username != null && jwtService.isTokenValid(token)){
UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
setAuthentication(userDetails, request);
}
}
filterChain.doFilter(request, response);
}
private String getTokenFromHeader(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
private void setAuthentication(UserDetails userDetails, HttpServletRequest request) {
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
CustomUserDetailsService:
package com.example.ecommerce.security;
import com.example.ecommerce.model.user.User;
import com.example.ecommerce.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
return new CustomUserDetails(user);
}
}
if it neccessery there is CustomUserDetails:
package com.example.ecommerce.security;
import com.example.ecommerce.model.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRole().getAuthorities();
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
}
then finally UserRepository:
package com.example.ecommerce.repository;
import com.example.ecommerce.model.user.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
Any idea ?
I have checked Entity relations and some different .properties configs. Is there any suggest to way out?
Ömer Özcan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.