ubuntu Sping Boot 循环引用已在application.properties中处理,但似乎被Java Sping Boot 可执行jar文件忽略

6yoyoihd  于 2023-10-17  发布在  Java
关注(0)|答案(1)|浏览(121)

所以这个案例是我使用Java Sping Boot 创建的一个简单的登录员工管理系统(非常基本,所以它足以进行登录-注销和CRUD操作)。我还尝试使用Spring Security来保护身份验证。
这是我的Java Sping Boot 应用程序的规范:

  • Spring工具套件4.18.0.RELEASE
  • Spring安全6
  • 使用Java 17
  • 构建在Linux ubuntu 22.04之上
  • application.properties已经默认位于SBTLEmpManSys/src/main/resources中的资源文件夹中

我将附上我的java文件相关的错误,application.properties,和pom.xml后,但这是我已经处理。我已经把这个代码spring.main.allow-circular-references=true在我的application.properties来处理这个错误,它实际上工作

  1. The dependencies of some of the beans in the application context form a cycle:
  2. ┌─────┐
  3. | securityConfiguration (field private org.springframework.security.config.annotation.web.builders.HttpSecurity org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.httpSecurity)
  4. | org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.httpSecurity defined in class path resource [org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]
  5. └─────┘

当我在Spring Tool Suite IDE中运行它时,一切都运行得很好。
但是问题发生在我把我的Java Sping Boot 应用程序打包到可执行的jar文件中之后。文件application.properties似乎被忽略了。
循环引用似乎发生在EmpServiceImpl.java中这行代码周围:

  1. @Service
  2. public class EmpServiceImpl implements EmpService {
  3. @Autowired
  4. private EmployeeRepository empRepDAO;
  5. //public EmpServiceImpl(@Lazy EmployeeRepository empRepDAO) { //ANNOTATION '@Lazy' is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
  6. public EmpServiceImpl(EmployeeRepository empRepDAO) {
  7. super();
  8. this.empRepDAO = empRepDAO;
  9. }
  10. ...[AND_SO_ON]

我运行jar文件的方式是通过终端进入target目录,然后用java -jar SBTLEmpManSys-0.0.1-SNAPSHOT.jar运行它。这是我运行应用程序时得到的错误片段。

  1. Application run failed
  2. org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empServiceImpl': Unsatisfied dependency expressed through field 'passwordEncoder': Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'httpSecurity': Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.httpSecurity' defined in class path resource [org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]: Failed to instantiate [org.springframework.security.config.annotation.web.builders.HttpSecurity]: Factory method 'httpSecurity' threw exception with message: Error creating bean with name 'passwordEncoder': Requested bean is currently in creation: Is there an unresolvable circular reference?

我想知道为什么错误消息说这个Requested bean is currently in creation: Is there an unresolvable circular reference?,因为它应该已经在application.properties中处理了。
有人能帮忙吗?任何帮助将非常感谢。谢谢各位;)
我的SecurityConfiguration.java

  1. package com.kastamer.sbtl.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.PropertySource;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. import org.springframework.security.web.SecurityFilterChain;
  11. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  12. import com.kastamer.sbtl.service.EmpService;
  13. @Configuration
  14. @PropertySource(value = "classpath:application.properties")
  15. @EnableWebSecurity
  16. public class SecurityConfiguration extends WebSecurityConfiguration {
  17. @Autowired
  18. public EmpService empService;
  19. @Bean
  20. public BCryptPasswordEncoder passwordEncoder() {
  21. // TODO Auto-generated method stub
  22. return new BCryptPasswordEncoder();
  23. }
  24. @Bean
  25. public SecurityFilterChain configure(HttpSecurity http) throws Exception {
  26. // TODO Auto-generated method stub
  27. http.authorizeHttpRequests((requests) -> requests.requestMatchers(
  28. "/registrasi",
  29. "/js**",
  30. "/css**",
  31. "/img**")
  32. .permitAll().anyRequest().authenticated())
  33. .formLogin((form) -> form.loginPage("/login").permitAll())
  34. .logout((logout) -> logout.invalidateHttpSession(true).clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").permitAll());
  35. return http.build();
  36. }
  37. }

这是我的服务文件'EmpServiceImpl.java':

  1. package com.kastamer.sbtl.service;
  2. import java.util.Arrays;
  3. import java.util.Collection;
  4. import java.util.List;
  5. import java.util.Optional;
  6. import java.util.stream.Collectors;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.annotation.Lazy;
  9. import org.springframework.data.domain.Page;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Pageable;
  12. import org.springframework.data.domain.Sort;
  13. import org.springframework.security.core.GrantedAuthority;
  14. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  15. import org.springframework.security.core.userdetails.UserDetails;
  16. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  17. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  18. import org.springframework.stereotype.Service;
  19. import com.kastamer.sbtl.model.EmpRole;
  20. import com.kastamer.sbtl.model.Employee;
  21. import com.kastamer.sbtl.repository.EmployeeRepository;
  22. import com.kastamer.sbtl.web.dto.EmpRegistrationDTO;
  23. @Service
  24. public class EmpServiceImpl implements EmpService {
  25. @Autowired
  26. private EmployeeRepository empRepDAO; //this is interface extend JpaRepository<Employee, Long>
  27. @Autowired
  28. private BCryptPasswordEncoder passwordEncoder;
  29. //@Autowired //THIS is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
  30. //public EmpServiceImpl(@Lazy EmployeeRepository empRepDAO) { //ANNOTATION '@Lazy' is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
  31. public EmpServiceImpl(EmployeeRepository empRepDAO) {
  32. super();
  33. this.empRepDAO = empRepDAO;
  34. }
  35. @Override
  36. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  37. // TODO Auto-generated method stub
  38. Employee pegawai = empRepDAO.findByEmail(username);
  39. if (pegawai == null) {
  40. throw new UsernameNotFoundException("Email atau kata sandi tidak cocok!");
  41. }
  42. return new org.springframework.security.core.userdetails.User(pegawai.getEmail(), pegawai.getPassword(), mapRolesToAuthority(pegawai.getRoles())); //return null;
  43. }
  44. @Override
  45. public Employee save(EmpRegistrationDTO empRegistrationDTO) {
  46. // TODO Auto-generated method stub
  47. Employee karyawan = new Employee(
  48. empRegistrationDTO.getFullName(),
  49. empRegistrationDTO.getEmail(),
  50. passwordEncoder.encode(empRegistrationDTO.getPassword()),
  51. Arrays.asList(new EmpRole("ROLE_USER")));
  52. return empRepDAO.save(karyawan); //return null;
  53. }
  54. @Override
  55. public void simpanPembaruanData(Employee employee) {
  56. // TODO Auto-generated method stub
  57. employee.setPassword(passwordEncoder.encode(employee.getPassword()));
  58. this.empRepDAO.save(employee);
  59. }
  60. private Collection<? extends GrantedAuthority> mapRolesToAuthority(Collection<EmpRole> roles) {
  61. // TODO Auto-generated method stub
  62. return roles.stream().map(role -> new SimpleGrantedAuthority(role.getNamaRole())).collect(Collectors.toList());
  63. }
  64. //PART POJOK KARYAWAN
  65. @Override
  66. public List<Employee> getAllEmployees() {
  67. // TODO Auto-generated method stub
  68. return empRepDAO.findAll(); //return null;
  69. }
  70. @Override
  71. public Employee getEmployeeById(long id) {
  72. // TODO Auto-generated method stub
  73. Optional<Employee> optEmp = empRepDAO.findById(id);
  74. Employee empl = null;
  75. if (optEmp.isPresent()) {
  76. empl = optEmp.get();
  77. } else {
  78. throw new RuntimeException("Karyawan dengan emp_id '" + id + "' tidak bisa ditemukan");
  79. }
  80. return empl; //return null;
  81. }
  82. @Override
  83. public void deleteEmployeeById(long id) {
  84. // TODO Auto-generated method stub
  85. this.empRepDAO.deleteById(id);
  86. }
  87. @Override
  88. public Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortAscOrDesc) {
  89. // TODO Auto-generated method stub
  90. Sort runut = sortAscOrDesc.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
  91. Pageable pageable = PageRequest.of(pageNo - 1, pageSize, runut);
  92. return this.empRepDAO.findAll(pageable); //return null;
  93. }
  94. }

这是我的application.properties

  1. spring.datasource.url=jdbc:postgresql://localhost:5432/myDB
  2. spring.datasource.username=[POSTGRES_USERNAME]
  3. spring.datasource.password=[POSTGRES_PASSWORD]
  4. spring.datasource.driver-class-name=org.postgresql.Driver
  5. spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
  6. spring.jpa.hibernate.ddl-auto=update
  7. logging.level.org.hibernate.sql=debug
  8. logging.level.org.hibernate.type=trace
  9. #spring.jpa.show-sql=true
  10. # Default user login and password for spring security web login page (if spring security is enabled)
  11. #spring.security.user.name=spring
  12. #spring.security.user.password=spring123
  13. #spring.security.user.roles=USER
  14. spring.main.allow-bean-definition-overriding=true
  15. spring.main.allow-circular-references=true
i2loujxw

i2loujxw1#

明白了!我终于解决了循环引用后,消除extends WebSecurityConfiguration从我的代码在文件SecurityConfiguration.java

相关问题