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

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

所以这个案例是我使用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来处理这个错误,它实际上工作

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  securityConfiguration (field private org.springframework.security.config.annotation.web.builders.HttpSecurity org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.httpSecurity)
↑     ↓
|  org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.httpSecurity defined in class path resource [org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]
└─────┘

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

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmployeeRepository empRepDAO;
    
    //public EmpServiceImpl(@Lazy EmployeeRepository empRepDAO) { //ANNOTATION '@Lazy' is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
    public EmpServiceImpl(EmployeeRepository empRepDAO) {
        super();
        this.empRepDAO = empRepDAO;
    }

...[AND_SO_ON]

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

Application run failed

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

package com.kastamer.sbtl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
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.WebSecurityConfiguration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.kastamer.sbtl.service.EmpService;

@Configuration
@PropertySource(value = "classpath:application.properties")
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfiguration {

    @Autowired
    public EmpService empService;
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        // TODO Auto-generated method stub
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.authorizeHttpRequests((requests) -> requests.requestMatchers(
                "/registrasi",
                "/js**",
                "/css**",
                "/img**")
                .permitAll().anyRequest().authenticated())
        .formLogin((form) -> form.loginPage("/login").permitAll())
        .logout((logout) -> logout.invalidateHttpSession(true).clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").permitAll());
        
        return http.build();
    }
}

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

package com.kastamer.sbtl.service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.kastamer.sbtl.model.EmpRole;
import com.kastamer.sbtl.model.Employee;
import com.kastamer.sbtl.repository.EmployeeRepository;
import com.kastamer.sbtl.web.dto.EmpRegistrationDTO;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmployeeRepository empRepDAO; //this is interface extend JpaRepository<Employee, Long>
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //@Autowired //THIS is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
    //public EmpServiceImpl(@Lazy EmployeeRepository empRepDAO) { //ANNOTATION '@Lazy' is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NOT WORKING
    public EmpServiceImpl(EmployeeRepository empRepDAO) {
        super();
        this.empRepDAO = empRepDAO;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        Employee pegawai = empRepDAO.findByEmail(username);
        
        if (pegawai == null) {
            throw new UsernameNotFoundException("Email atau kata sandi tidak cocok!");
        }
        
        return new org.springframework.security.core.userdetails.User(pegawai.getEmail(), pegawai.getPassword(), mapRolesToAuthority(pegawai.getRoles())); //return null;
    }

    @Override
    public Employee save(EmpRegistrationDTO empRegistrationDTO) {
        // TODO Auto-generated method stub
        Employee karyawan = new Employee(
                empRegistrationDTO.getFullName(),
                empRegistrationDTO.getEmail(),
                passwordEncoder.encode(empRegistrationDTO.getPassword()),
                Arrays.asList(new EmpRole("ROLE_USER")));
        
        return empRepDAO.save(karyawan); //return null;
    }

    @Override
    public void simpanPembaruanData(Employee employee) {
        // TODO Auto-generated method stub
        employee.setPassword(passwordEncoder.encode(employee.getPassword()));
        
        this.empRepDAO.save(employee);
    }
    
    private Collection<? extends GrantedAuthority> mapRolesToAuthority(Collection<EmpRole> roles) {
        // TODO Auto-generated method stub
        return roles.stream().map(role -> new SimpleGrantedAuthority(role.getNamaRole())).collect(Collectors.toList());
    }

    //PART POJOK KARYAWAN
    @Override
    public List<Employee> getAllEmployees() {
        // TODO Auto-generated method stub
        return empRepDAO.findAll(); //return null;
    }

    @Override
    public Employee getEmployeeById(long id) {
        // TODO Auto-generated method stub
        Optional<Employee> optEmp = empRepDAO.findById(id);
        Employee empl = null;
        
        if (optEmp.isPresent()) {
            empl = optEmp.get();
        } else {
            throw new RuntimeException("Karyawan dengan emp_id '" + id + "' tidak bisa ditemukan");
        }
        
        return empl; //return null;
    }

    @Override
    public void deleteEmployeeById(long id) {
        // TODO Auto-generated method stub
        this.empRepDAO.deleteById(id);
    }

    @Override
    public Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortAscOrDesc) {
        // TODO Auto-generated method stub
        Sort runut = sortAscOrDesc.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
        
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, runut);
        
        return this.empRepDAO.findAll(pageable); //return null;
    }
}

这是我的application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/myDB
spring.datasource.username=[POSTGRES_USERNAME]
spring.datasource.password=[POSTGRES_PASSWORD]
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

spring.jpa.hibernate.ddl-auto=update

logging.level.org.hibernate.sql=debug
logging.level.org.hibernate.type=trace
#spring.jpa.show-sql=true

# Default user login and password for spring security web login page (if spring security is enabled)
#spring.security.user.name=spring
#spring.security.user.password=spring123 
#spring.security.user.roles=USER

spring.main.allow-bean-definition-overriding=true
spring.main.allow-circular-references=true
i2loujxw

i2loujxw1#

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

相关问题