Spring boot 如何在加载配置文件之前在spring容器中注册类

Spring boot 如何在加载配置文件之前在spring容器中注册类,spring-boot,spring-security,Spring Boot,Spring Security,这是我在webapp模块中的websecurity类 package com.ioyota.shareitnamchi.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan;

这是我在webapp模块中的websecurity类

    package com.ioyota.shareitnamchi.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.crypto.bcrypt.BCryptPasswordEncoder;

import com.ioyota.core.util.AppConstants;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackages="com.ioyota")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private com.ioyota.user.security.**CustomAuthenticationProvider** CustomAuthenticationProvider;


    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*http.authorizeRequests().antMatchers("/resources/**", "/registration","/greeting","/ignore/**","/*").permitAll()
                .antMatchers("/admin/**")
                .authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();
        http.csrf().disable();*/

        // Page with login form is served as /login.html and does a POST on /login
          http.formLogin().loginPage("/login").loginProcessingUrl("/login").permitAll();
          // The UI does a POST on /logout on logout
          http.logout().logoutUrl("/logout");
          // The ui currently doesn't support csrf
          http.csrf().disable();

          http.authorizeRequests().antMatchers(AppConstants.NAMCHI_ADMIN_URL+"/**").authenticated();

          // Requests for the login page and the static assets are allowed
          http.authorizeRequests()

              .antMatchers("/resources/**", "/registration","/greeting","/ignore/**","/**")
              .permitAll();


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(this.CustomAuthenticationProvider);
    }



}
自定义验证器在其他模块中定义。现在,当我在STS中使用运行方式运行我的应用程序时,spring boot应用程序可以正常工作。但如果我以spring boot:运行方式运行它,则会出现此错误

org.springframework.beans.factory.BeanCreationException:错误 正在创建文件中定义了名为“repoConf”的bean [F:\namchi26july\shareitnamchi system\shareitnamchi\shareitnamchi webapp\target\classes\com\ioyota\shareitnamchi\security\WebSecurityConfig.class]: 合并bean定义后处理失败;嵌套异常是 java.lang.IllegalStateException:未能内省类 [com.ioyota.shareitnamchi.security.WebSecurityConfig]来自ClassLoader [java.net。URLClassLoader@25527c7d]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:560) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.PreInstanceSingleton(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] com.ioyota.App.main(App.java:26)[classes/:na] sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法) ~(na:1.8.0_161)at invoke(NativeMethodAccessorImpl.java:62) ~(na:1.8.0_161)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 位于java.lang.reflect.Method.invoke(Method.java:498)的~[na:1.8.0_161] ~(na:1.8.0_161)at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:496) [spring-boot-maven-plugin-2.0.0.RELEASE.jar:2.0.0.RELEASE] java.lang.Thread.run(Thread.java:748)[na:1.8.0_161]由以下原因引起: java.lang.IllegalStateException:未能内省类 [com.ioyota.shareitnamchi.security.WebSecurityConfig]来自ClassLoader [java.net。URLClassLoader@25527c7d]在 org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:759) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.util.ReflectionUtils.doWithLocalFields(ReflectionUtils.java:691) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.buildPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:410) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:394) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:332) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1016) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]。。。21通用框架 由于以下原因而忽略:java.lang.NoClassDefFoundError: Lcom/ioyota/user/security/CustomAuthenticationProvider;在 java.lang.Class.getDeclaredFields0(本机方法)~[na:1.8.0_161]at java.lang.Class.privateGetDeclaredFields(Class.java:2583) ~[na:1.8.0_161]位于java.lang.Class.getDeclaredFields(Class.java:1916) ~(na:1.8.0_161)at org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:754) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]。。。27普通
 package com.ioyota.user.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import com.ioyota.core.dto.UserDTO;
import com.ioyota.core.entity.RolePermission;
import com.ioyota.user.repository.RolePermissionRepository;
import com.ioyota.user.service.UserService;
@Component
@DependsOn("repoConf")
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName().trim();
        UserDTO user = null;
        try {
            user = userService.findByUsername(userName);
        } catch (Exception e) {

        }
        if (user == null) {
            throw new UsernameNotFoundException("Username or password is not correct");
        }
        if (!bCryptPasswordEncoder.matches(authentication.getCredentials().toString().trim(), user.getPassword())) {
            throw new BadCredentialsException("Username or password is not correct");
        }
        // Authenticate the user based on your custom logic

        List<RolePermission> rolePermissionsList = rolePermissionRepository.findByRoleId(user.getRole().getRoleId());
        Set<GrantedAuthority> authList = new HashSet<GrantedAuthority>();
        for (RolePermission rolePermission : rolePermissionsList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(
                    rolePermission.getPermissionId() + "");
            authList.add(simpleGrantedAuthority);
        }
        return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials().toString(), authList);

    }

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}