I am writing a REST MVC application. I'm using Spring Boot and Hibernate. For protection, I decided to add Spring Security and JWT to the project.
I use BCryptEncoder to encode the password. Accordingly, I have it in the JWTTokenProvider class as a bean. I need to inject PasswordEncoder into the UserService class, but I can't. I understand the reason, but I don’t know how to fix it.
UserSevice:
#RequiredArgsConstructor
#Service
public class UserService {
private final UserRepository userRepository;
private final UserMapper userMapper;
private final PasswordEncoder passwordEncoder;
public UserDTO registration (RegistrationUserDTO registrationUserDTO){
User user = new User();
user.setName(registrationUserDTO.getName());
user.setLastName(registrationUserDTO.getLastName());
user.setLogin(registrationUserDTO.getLogin());
user.setMail(registrationUserDTO.getMail());
user.setPassword(passwordEncoder.encode(registrationUserDTO.getPassword()));
user.setRole(Role.CUSTOMER);
userRepository.save(user);
return userMapper.userToUserDTO(user);
}
}
JwtTokenProvider:
#RequiredArgsConstructor
#Component
public class JwtTokenProvider {
// Fields
//
private final UserDetailsService userDetailsService;
#Value("${jwt.token.secret}")
private String secret;
#Value("${jwt.token.expired}")
private Long validityInMilliSeconds;
// METHODS
//
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(8);
}
#PostConstruct
protected void init() {
secret = Base64.getEncoder().encodeToString(secret.getBytes());
}
/**
*
* #param login
* #param role
* #return ТОКЕН
*/
public String createToken(String login, Role role) {
Claims claims = Jwts.claims().setSubject(login);
claims.put("roles", role.name());
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliSeconds);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public Authentication getAuthentication(String token) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(getLogin(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
public String getLogin(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateToken(String token) {
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return !claims.getBody().getExpiration().before(new Date());
} catch (JwtException | IllegalArgumentException e) {
throw new JwtAuthenticationException("JWT token is expired or invalid");
}
}
/**
*
* #param req
* #return bearerToken
*/
public String resolveToken(HttpServletRequest req) {
String bearerToken = req.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}
JwtUserDetailsService:
#Slf4j
#Service
#RequiredArgsConstructor
public class JwtUserDetailsService implements UserDetailsService {
private final UserService userService;
#Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userService.findByLogin(login);
JwtUser jwtUser = JwtUserFactory.create(user);
log.info("IN loadUserByUsername - user with login: {} successfully loaded", login);
return jwtUser;
}
}
Logs:
2020-08-20 11:59:44.964 WARN 15396 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig' defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\config\SecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtTokenProvider' defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\security\jwt\JwtTokenProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtUserDetailsService' defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\security\JwtUserDetailsService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'jwtTokenProvider': Requested bean is currently in creation: Is there an unresolvable circular reference?
2020-08-20 11:59:44.964 INFO 15396 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-08-20 11:59:49.500 INFO 15396 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
Exception in thread "task-2" org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'delegatingApplicationListener': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:212)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245)
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:99)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
2020-08-20 11:59:49.525 INFO 15396 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-08-20 11:59:49.532 INFO 15396 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-08-20 11:59:49.589 INFO 15396 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-08-20 11:59:49.598 INFO 15396 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-20 11:59:49.628 INFO 15396 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-20 11:59:49.659 ERROR 15396 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
securityConfig defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\config\SecurityConfig.class]
┌─────┐
| jwtTokenProvider defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\security\jwt\JwtTokenProvider.class]
↑ ↓
| jwtUserDetailsService defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\security\JwtUserDetailsService.class]
↑ ↓
| userService defined in file [D:\JetBrainsProjects\Coffeetearea\build\classes\java\main\ru\coffeetearea\service\UserService.class]
└─────┘
Process finished with exit code 1
The problem is you are injecting something, the JwtTokenProvider in an #Configuration class that produces a bean that is needed by the JwtTokenProvider. So the JwtTokenProvider needs something provided by the security configuration while the SecurityConfig can only be created when it has a JwtTokenProvider hence a circular dependency.
Remove #Component from the JwtTokenProvider and create an #Bean method in the SecurityConfig (or whatever it is called) which creates the JwtTokenProvider.
It is also not recommended to use #Bean methods in #Components so move that to the SecurityConfig as well.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(8);
}
#Bean
public JwtTokenProvider jwtTokenProvider(UserDetailsService userDetailsService) {
return new JwtTokenProvider(userDetailsService);
}
// other config
}
Now there probably still is an issue as your JwtUserDetailsService needs the UserService which needs the PasswordEncoder and this again creates a circular reference. You might be better of injecting the UserRepository into your JwtUserDetailsService and use that to get the user by the login. I'm assuming that the UserService simply delegates to the UserRepository.findByLogin method.
#Slf4j
#Service
#RequiredArgsConstructor
public class JwtUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userRepository.findByLogin(login);
if (user != null) {
JwtUser jwtUser = JwtUserFactory.create(user);
log.info("IN loadUserByUsername - user with login: {} successfully loaded", login);
return jwtUser;
} else {
throw new UsernameNotFoundException("Unknown user '"+login+"'");
}
}
}
NOTE: Your UserDetailsService didn't honour the contract (no user found should throw an UsernameNotFoundException. The modified one does honour that contract.
Related
I am working on Spring project. In this project I have password encoder bean.
#Configuration
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
public AppSecurityConfiguration() {
System.out.println("\n\n " + getClass().getName() + "\n\n\n");
}
#Autowired
private UserService userService;
#Bean
public PasswordEncoder defaultPasswordEncoder() {
System.out.println("\n\n\n bean is created!!!!! \n\n\n");
return new BCryptPasswordEncoder();
}
// other configurations
}
And the class where injection is required is this,
#Component
public class Encoders {
private static PasswordEncoder bCryptPasswordEncoder;
#Autowired
private PasswordEncoder defaultPasswordEncoder;
public Encoders() throws UnsupportedEncodingException {
System.out.println("\n\n\n " + (defaultPasswordEncoder == null) + " \n\n\n"); // this has problem, as defaultPasswordEncoder is null.
Encoders.bCryptPasswordEncoder = defaultPasswordEncoder;
}
// other methods
}
The defaultPasswordEncoder in the above class is null even though I have autowired this field.
The logs are showing that although the appSecurityConfiguration bean was made before encoder bean still the defaultPasswordEncoder bean is being created after encoder bean.
Here is the log,
2021-10-31 10:28:51.644 DEBUG 58508 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'appSecurityConfiguration'
com.clone.postmanc.security.AppSecurityConfiguration$$EnhancerBySpringCGLIB$$9529a353
.
.
.
.
2021-10-31 10:28:51.695 DEBUG 58508 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'encoders'
true // coming from Encoder#Encoder showing that
// defaultPasswordEncoder bean is null
2021-10-31 10:28:51.697 DEBUG 58508 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'defaultPasswordEncoder'
bean is created!!!!! // coming from AppSecurityConfiguration#defaultPasswordEncoder
I have also tried depends on annotation,
#Component
#DependsOn("defaultPasswordEncoder")
public class Encoders {
// rest is same
}
Now in logs defaultPasswordEncoder bean is being created before encoders but still the injection is not happening and the PasswordEncoder defaultPasswordEncoder field is null.
Here is the log,
2021-10-31 10:28:51.644 DEBUG 58508 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'appSecurityConfiguration'
com.clone.postmanc.security.AppSecurityConfiguration$$EnhancerBySpringCGLIB$$9529a353
.
.
.
2021-10-31 10:51:27.323 DEBUG 59592 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'defaultPasswordEncoder'
bean is created!!!!!
2021-10-31 10:51:27.327 DEBUG 59592 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'encoders'
true // still the field is null.
Can someone tell what is happening? And to resolve this issue?
Use constructor injection instead of property injection
public Encoders(PasswordEncoder defaultPasswordEncoder)
Then the bean will be available in constructor.
When I'm trying to implement to login part of my API and try to run it, I got many errors like bellow :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-02-12 02:23:23.314 ERROR 25840 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\controllers\UserController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\security\config\WebSecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\services\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1206) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.3.jar:5.3.3]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\security\config\WebSecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\services\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356) ~[spring-beans-5.3.3.jar:5.3.3]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in file [C:\Users\chafy\Desktop\cub\back\target\classes\com\cesi\cuberil\services\UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356) ~[spring-beans-5.3.3.jar:5.3.3]
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.3.jar:5.3.3]
I'm new to Spring se I don't really know what the error means.
here the following classes :
UserController :
#RestController
#RequestMapping(path="api/v1/user")
#AllArgsConstructor
#CrossOrigin(origins = "*")
public class UserController implements Routes {
private final AuthenticationManager authenticationManager;
private final RegistrationService registrationService;
#PostMapping(registration)
public String register(#RequestBody RegistrationRequest request){
return registrationService.register(request);
}
#PostMapping(login)
public ResponseEntity<?> login(#Valid #RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUserName(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
User myUserDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<String> roles = myUserDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok("OKKKK CONNECté");
}
#PostMapping(resetPassword)
public String resetPassword() {
return "Password reset";
}
#GetMapping(path = confirm)
public String confirm(#RequestParam("token") String token) {
return registrationService.confirmToken(token);
}
}
UserService :
#Service
#AllArgsConstructor
public class UserService implements UserDetailsService {
private final static String USER_NOT_FOUND_MESSAGE = "user with email %s not found";
private final UserRepository userRepository;
private final ConfirmationTokenService confirmationTokenService;
private final AuthenticationManager authenticationManager;
#Override
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException(String.format(USER_NOT_FOUND_MESSAGE, email)));
}
public String signUpUser(User user) {
boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
if (userExists) {
throw new IllegalStateException("Email already taken");
}
String encodedPassword = bCryptPasswordEncoder().encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
String token = UUID.randomUUID().toString();
//TODO: Send Confirmation Token
ConfirmationToken confirmationToken = new ConfirmationToken(
token,
LocalDateTime.now(),
LocalDateTime.now().plusMinutes(15),
user
);
confirmationTokenService.saveConfirmationToken(confirmationToken);
//TODO: SEND EMAIL
return "Token: " + token + "\nFirstname: " + user.getFirstName() + "\nLastname: " + user.getLastName() +
"\nUsername: " + user.getUsername() + "\nEmail: " + user.getEmail();
}
public int enableAppUser(String email) {
return userRepository.enableAppUser(email);
}
public AuthenticationResponse login(LoginRequest loginRequest) {
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUserName(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authenticate);
return new AuthenticationResponse(loginRequest.getUserName());
}
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
WebSecurityConfig :
#Configuration
#AllArgsConstructor
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/api/v*/**").permitAll()
.anyRequest()
.authenticated().and()
.formLogin();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userService)
.passwordEncoder(passwordEncoder());
}
#Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
I don't understand the meaning of : Is there an unresolvable circular reference?
I've remove all #Autowiredannotationd because Spring will attempt to find a bean of matching type. I through that was the problem but no.
The Spring uses de Inversion of Control principle, that means you don't have to create your objects and you can add them through Dependency Injection.
When you inject dependencies in the WebSecurityConfig through Lombok's #AllArgsConstructor constructor you're telling to Spring inject those beans.
At that phase, it doesn't have the required bean "AuthenticationManager" for the UserService bean.
The solution is to inject the UserService through method's parameter using autowired
#Override
#Autowired
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder, UserService userService) throws Exception {
authenticationManagerBuilder.userDetailsService(userService)
.passwordEncoder(passwordEncoder());
}
and remove the class field userService.
Wrong way
#SpringBootApplication
public class DemoApplication {
UserService userService;
public DemoApplication(UserService userService) {
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public TestService testService() {
return new TestService();
}
}
Log
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| demoApplication
↑ ↓
| userService defined in file [...\target\classes\com\example\demo\UserService.class]
└─────┘
Solution
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Autowired
public void userService(UserService userService) {
System.out.println("UserService Injected: " + userService);
}
#Bean
public TestService testService() {
return new TestService();
}
}
#Service
public class UserService {
public UserService(TestService testService) {
System.out.println("User Service created using: " + testService);
}
}
public class TestService {
public TestService() {
System.out.println("TestService created");
}
#Override
public String toString() {
return "Test Service";
}
}
Log
TestService created
User Service created using: Test Service
UserService Injected: com.example.demo.UserService#29629fbb
everyone. I am new to WebMvcTest, and am learning to write a PostControllerTest. While the project runs well, the test does not work.
2017-05-31 10:08:09.490 INFO 5768 --- [ main] nz.p2.controller.PostControllerTest : Starting PostControllerTest on My-PC with PID 5768 (started by Me in C:\...)
2017-05-31 10:08:09.491 INFO 5768 --- [ main] nz.p2.controller.PostControllerTest : No active profile set, falling back to default profiles: default
2017-05-31 10:08:10.989 INFO 5768 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#2a8d39c4: startup date [Wed May 31 10:08:10 NZST 2017]; root of context hierarchy
2017-05-31 10:08:12.788 INFO 5768 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-05-31 10:08:13.311 WARN 5768 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'reCaptchaAuthenticationFilter': Unsatisfied dependency expressed through field 'reCaptchaService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'nz.p2.captcha.ReCaptchaService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-05-31 10:08:13.326 INFO 5768 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-05-31 10:08:13.534 ERROR 5768 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field reCaptchaService in nz.p2.captcha.ReCaptchaAuthenticationFilter required a bean of type 'nz.p2.captcha.ReCaptchaService' that could not be found.
Action:
Consider defining a bean of type 'nz.p2.captcha.ReCaptchaService' in your configuration.
It tells me to do something with the ReCaptchaService; which isn't used with the PostController. Given the simplifed Controller class:
#Controller
public class PostController {
#Autowired
private PostService postService;
#RequestMapping(value = URI_POST_POST, method = RequestMethod.GET)
public ModelAndView get(#Valid Long mkid) throws IOException {
// do somthing here using postService;
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(URI_POST_POST);
modelAndView.addObject("abc", abc);
return modelAndView;
}
}
The PostControllerTest class is here:
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = PostController.class)
public class PostControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private PostController postControllereMock;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(webApplicationContext).build();
}
#Test
public void testList() throws Exception {
assertThat(this.postControllereMock).isNotNull();
mockMvc.perform(MockMvcRequestBuilders.get(URI_POST_POST + "?mkid=8044022272730561994"))
.andExpect(status().isOk())
.andExpect(content().contentType("text/html;charset=UTF-8"))
.andExpect(view().name(URI_POST_POST))
.andExpect(MockMvcResultMatchers.view().name(URI_POST_POST))
.andExpect(content().string(Matchers.containsString("I have put together some image galleries")))
.andDo(print());
}
}
I have to mention that the reCaptchaService is #Autowired in the ReCaptchaAuthenticationFilter, and the latter one is #Autowired and used here:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.
// tl; nw
.and().csrf().disable()
.addFilterBefore(reCaptchaAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
// tl; nw
}
}
So, in this case, how can I test the PostController?
I am new to spring and trying to create a web app using spring boot and jsp which I can deploy using tomcat8 on a raspberry pi. I can deploy my app through sts on an embedded tomcat instance and I can also deploy a war file to Jenkins without any errors. However, when I add the war to tomcat8 webapps folder and start tomcat I get the following error:
2016-04-19 10:54:41.384 WARN 5525 --- [ost-startStop-1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.rcctv.controllers.UserController.setUserService(com.rcctv.services.UserService); nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl' defined in file [/usr/share/tomcat8/webapps/RaspberryCCTV-0.0.1-SNAPSHOT/WEB-INF/classes/com/rcctv/services/UserServiceImpl.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [org.springframework.security.crypto.password.PasswordEncoder]: : Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'userServiceImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'userServiceImpl': Requested bean is currently in creation: Is there an unresolvable circular reference?
I have tried annotating my configuration class with #Lazy and added setter methods to my userServiceImpl class but I still got the issue. Any help would be greatly appreciated?
webConfig class
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${rememberMe.privateKey}")
private String rememberMeKey;
#Value("${spring.profiles.active}")
private String env;
#Resource
private UserDetailsService userService;
#Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
#Bean
public RememberMeServices rememberMeServices() {
TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices(rememberMeKey, userService);
return rememberMeServices;
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/",
"/home",
"/error",
"/signup",
"/forgot-password",
"/reset-password/*",
"/public/**",
"/users/*").permitAll()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/raspberrycctv")
.permitAll().and()
.rememberMe().key(rememberMeKey).rememberMeServices(rememberMeServices()).and()
.logout()
.permitAll();
if (!env.equals("dev"))
http.requiresChannel().anyRequest().requiresSecure();
}
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
authManagerBuilder.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
}
UserSeviceImpl
#Service
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class UserServiceImpl implements UserService, UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
private UserRepository userRepository;
private PasswordEncoder passwordEncoder;
private MailSender mailSender;
#Autowired
public UserServiceImpl(UserRepository userRepository,
PasswordEncoder passwordEncoder,
MailSender mailSender) {
this.mailSender = mailSender;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
#Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Autowired
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
#Autowired
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
#Override
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void signup(SignupForm signupForm) {
final User user = new User();
user.setEmail(signupForm.getEmail());
user.setName(signupForm.getName());
user.setPassword(passwordEncoder.encode(signupForm.getPassword()));
user.getRoles().add(Role.UNVERIFIED);
user.setVerificationCode(RandomStringUtils.randomAlphanumeric(16));
userRepository.save(user);
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
#Override
public void afterCommit() {
try {
String verifyLink = Utilities.hostUrl() + "/users/" + user.getVerificationCode() + "/verify";
mailSender.send(user.getEmail(), Utilities.getMessage("verifySubject"), Utilities.getMessage("verifyEmail", verifyLink));
logger.info("Verification mail to " + user.getEmail() + " queued.");
} catch (MessagingException e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
}
I think you should go through Spring Reference about IoC container.
WebSecurityConfig class requires UserDetailsService, which is implemented by UserServiceImpl. Also, UserServiceImpl requires PasswordEncoder which is provided by WebSecurityConfig. This causes a circular reference. Removing constructor injection should be enough to resolve your problem.
Side note: Try not to use constructor injection. Spring is clever when it comes to DI, but if you use constructor injection you are forcing spring to use your way. This can also cause circular reference errors.
I recommend you to at least skim this article: https://steveschols.wordpress.com/2012/06/05/i-was-wrong-constructor-vs-setter-injection/
I'm converting a controller to the newer annotation version. In the old version I used to specify the init method in springmvc-servlet.xml using:
<beans>
<bean id="myBean" class="..." init-method="init"/>
</beans>
How can I specify the init method using the annotation version?
You can use
#PostConstruct
public void init() {
// ...
}
Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.
There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.
If you are using #Bean you can reference by initMethod, like this.
#Configuration
public class BeanConfiguration {
#Bean(initMethod="init")
public BeanA beanA() {
return new BeanA();
}
}
public class BeanA {
// method to be initialized after context is ready
public void init() {
}
}
If you are using #Component you can annotate with #EventListener like this.
#Component
public class BeanB {
#EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
}
}
In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust #PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, #PostConstruct then autowired setters. I solved it with #EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.
I have two classes (#Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.
#Component
public class BeanA implements InitializingBean {
private BeanB beanB;
public BeanA() {
log.debug("Created...");
}
#PostConstruct
private void postConstruct() {
log.debug("#PostConstruct");
}
#Autowired
public void setBeanB(BeanB beanB) {
log.debug("#Autowired beanB");
this.beanB = beanB;
}
#Override
public void afterPropertiesSet() throws Exception {
log.debug("afterPropertiesSet()");
}
#EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
log.debug("#EventListener");
}
}
This is the log output showing the order of the calls when the container starts.
2018-11-30 18:29:30.504 DEBUG 3624 --- [ main] com.example.demo.BeanA : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [ main] com.example.demo.BeanB : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [ main] com.example.demo.BeanB : #Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanB : #PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanB : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : #Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : #PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [ main] com.example.demo.BeanA : #EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [ main] com.example.demo.BeanB : #EventListener
As you can see #EventListener is run last after everything is ready and configured.
#PostConstruct、implement InitializingBean、specify init-method they have call orders. So you can't use them to replace init-method. You can try this:
#Bean(initMethod = "init")
public MyBean mybean() {
return new MyBean();
}
class MyBean {
public void init() {
System.out.println("MyBean init");
}
}
in your class, you can declare a method named init().
Refer to:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#:~:text=Multiple%20lifecycle%20mechanisms%20configured%20for%20the%20same%20bean%2C%20with%20different%20initialization%20methods%2C%20are%20called%20as%20follows%3A
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}