java - Spring安全配置: AlreadyBuiltException: This object has already been built

标签 java spring-mvc spring-boot

我是这个项目的新手,我尝试在本地计算机中运行它,并在 ubuntu 16.04LTS java api Spring 安全错误上收到此错误。似乎也没有什么问题。

我的安全配置

@Configuration
@EnableWebSecurity
@Profile("production")
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserAuthorizationService userAuthorizationService;

@Autowired
private DataSource dataSource;

@Autowired
private ConfigurationParamsService configurationParamsService;

@Autowired
private AccessDeniedHandler oauthAccessDeniedHandler;

@Autowired
private AccessDecisionManager accessDecisionManager;

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/internal/v1/user/signup",
            "/api/internal/v1/user/activate",
            "/api/internal/v1/user/changePassword",
            "/api/internal/v1/user/password/reset",
            "/api/internal/v1/user/verifyPassword",
            "/api/internal/v1/accounts/activate",
            "/api/internal/v1/user/resend",
            "/api/internal/v1/user/quick_signup");
}

@Override
public void configure(HttpSecurity http) throws Exception {

    http.antMatcher("/api/internal/v1/user/login").csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/internal/v1/user/login").permitAll();

    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).accessDeniedHandler(oauthAccessDeniedHandler).and().antMatcher("/api/v3/oauth2/auth**").csrf().disable()
            .authorizeRequests().accessDecisionManager(accessDecisionManager).requestMatchers(new AntPathRequestMatcher("/api/v3/oauth2/auth")).authenticated();

    http.rememberMe().rememberMeServices(rememberMeServices())
            .tokenValiditySeconds(Integer.parseInt(configurationParamsService.getRememberMeTokenValiditySeconds()));

}

@Bean
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public CustomEntryPoint authenticationEntryPoint() {
    return new CustomEntryPoint();
}

@Bean
public RememberMeServices rememberMeServices() {
    PersistentTokenBasedRememberMeServices rememberMeServices = new PersistentTokenBasedRememberMeServices(configurationParamsService.getRememberMeKey(), userAuthorizationService,
            tokenRepository());
    rememberMeServices.setAlwaysRemember(true);
    rememberMeServices.setCookieName(configurationParamsService.getRememberMeCookieName());
    rememberMeServices.setTokenValiditySeconds(Integer.parseInt(configurationParamsService.getRememberMeTokenValiditySeconds()));
    return rememberMeServices;
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    super.authenticationManagerBean();
    List<AuthenticationProvider> providers = new ArrayList<>();
    providers.add(rememberMeAuthenticationProvider());

    return new ProviderManager(providers);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userAuthorizationService);
    auth.authenticationProvider(rememberMeAuthenticationProvider());
}

@Bean
public PersistentTokenRepository tokenRepository() {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    return tokenRepository;
}

@Bean
public RememberMeAuthenticationFilter rememberMeFilter() throws Exception {
    RememberMeAuthenticationFilter rememberMeFilter = new RememberMeAuthenticationFilter(authenticationManagerBean(), rememberMeServices());

    return rememberMeFilter;
}

@Bean
public AuthenticationProvider rememberMeAuthenticationProvider() {
    return new RememberMeAuthenticationProvider(configurationParamsService.getRememberMeKey());
}
}

我的 Gradle 构建

buildscript {
ext {
    springBootVersion = '1.4.0.RELEASE'
}
repositories {
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE")
}
 }


apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "jacoco"

apply plugin: 'maven'

group = 'com.trackimo.server'
version = '0.0.0.1'

// Uses JDK 8
sourceCompatibility = 1.8
targetCompatibility = 1.8

// 1. Get dependencies from Maven local repository
// 2. Get dependencies from Maven central repository
repositories {
mavenLocal()
mavenCentral()
maven {
    url 'http://repo.spring.io/snapshot'
}
}
ext {

logbackVersion = '1.1.3'
jsonDocVersion = '1.1.13'
hibernateVersion = '4.3.11.Final'
servletVersion = '3.1.0'
mandrillVersion = '0.0.5'
jodaTimeVersion = '2.8'
mokitoVersion = '1.9.5'
jsonPathVersion = '2.1.0'
hamcrestVersion = '1.3'
junitVersion = '4.11'
springOAuth2Version = '2.0.8.RELEASE'
dbUnitVersion = '2.5.1'
springtestdbunitVersion = '1.2.1'
springRedisDataVersion = '1.5.2.RELEASE'
redisClientVersion = '2.7.3'
quartzVersion = '2.2.1'
springContextVersion = '4.2.3.RELEASE'
commonsClientVersion = '3.1'
commonsUploadVersion = '1.3.1'
commonsIoVersion = '2.4'
kmlVersion = '2.2.1'
csvVersion = '1.2'
mailVersion = '1.4.7'
commonsLang3Version = '3.4'
cronparserVersion = '2.8'
brainTreePaymentsVersion = '2.52.0'
apachePioVersion = '3.13'
luceneVersion = '4.10.4'
ehcacheVersion = '2.6.11'
commonsValidator = '1.4.1'
airbrakeVersion = '2.2.8'
airbrakeLogbackVersion = '1.0.1'
}
configurations {
providedRuntime
}


dependencies {

// Amazon sqs dependency
compile "com.amazonaws:aws-java-sdk-sqs:1.10.27"

//spring configuration
compile "org.springframework:spring-context:${springContextVersion}"
compile "org.springframework:spring-context-         support:${springContextVersion}"

compile('org.springframework.boot:spring-boot-starter-web')
//compile('org.springframework.boot:spring-boot-starter-data-elasticsearch')
compile('org.elasticsearch:elasticsearch:2.2.0')
compile('com.spatial4j:spatial4j:0.4.1')
compile "com.vividsolutions:jts:1.13"

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.hibernate:hibernate-validator')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
runtime("mysql:mysql-connector-java")
runtime('com.h2database:h2')
//Social Dependencies
compile('org.springframework.social:spring-social-config')
compile('org.springframework.social:spring-social-core')
compile('org.springframework.social:spring-social-security')
compile('org.springframework.social:spring-social-web')
compile('org.springframework.social:spring-social-facebook:2.0.3.RELEASE')
compile('org.springframework.social:spring-social-google:1.0.0.RELEASE')
compile('org.springframework.social:spring-social-twitter:1.1.0.RELEASE')
compile('org.apache.httpcomponents:httpclient:4.3.6')

compile "redis.clients:jedis:${redisClientVersion}"
compile "org.springframework.data:spring-data-redis:${springRedisDataVersion}"

//spring security
compile "org.springframework.security.oauth:spring-security-oauth2:${springOAuth2Version}"

compile 'com.googlecode.json-simple:json-simple:1.1'

compile "org.hibernate:hibernate-ehcache:${hibernateVersion}"
compile "net.sf.ehcache:ehcache-core:${ehcacheVersion}"

compile "ch.qos.logback:logback-classic:${logbackVersion}"


compile "commons-httpclient:commons-httpclient:${commonsClientVersion}"
compile "commons-fileupload:commons-fileupload:${commonsUploadVersion}"
compile "commons-io:commons-io:${commonsIoVersion}"
compile "org.apache.commons:commons-lang3:${commonsLang3Version}"
compile "commons-validator:commons-validator:${commonsValidator}"

compile "com.mandrillapp.wrapper.lutung:lutung:${mandrillVersion}"

compile "org.quartz-scheduler:quartz:${quartzVersion}"
compile "org.quartz-scheduler:quartz-jobs:${quartzVersion}"

compile "javax.mail:mail:${mailVersion}"

compile "org.apache.commons:commons-csv:${csvVersion}"

compile "joda-time:joda-time:${jodaTimeVersion}"

//jsondoc configuration
compile "org.jsondoc:jsondoc-core:${jsonDocVersion}",
        "org.jsondoc:jsondoc-springmvc:${jsonDocVersion}"

compile "org.dbunit:dbunit:${dbUnitVersion}"
compile "com.github.springtestdbunit:spring-test-dbunit:${springtestdbunitVersion}"


compile "de.micromata.jak:JavaAPIforKml:${kmlVersion}"

compile "com.braintreepayments.gateway:braintree-java:${brainTreePaymentsVersion}"
compile "com.twilio.sdk:twilio-java-sdk:3.4.5"

compile "org.apache.poi:poi:${apachePioVersion}"

compile 'com.paypal.sdk:adaptivepaymentssdk:2.8.117'

compile 'com.paypal.sdk:merchantsdk:2.14.117'

compile 'com.paypal.sdk:paypal-core:1.7.0'

compile 'com.paypal.sdk:rest-api-sdk:1.4.1'

compile 'org.projectlombok:lombok:1.16.6'
compile 'com.zaxxer:HikariCP:2.5.1'
runtime "io.airbrake:airbrake-java:${airbrakeVersion}"
compile "net.anthavio:airbrake-logback:${airbrakeLogbackVersion}"




testCompile("junit:junit:${junitVersion}") {
    testCompile("org.springframework.boot:spring-boot-starter-test")
    testCompile "com.jayway.jsonpath:json-path:${jsonPathVersion}"
    "com.jayway.jsonpath:json-path-assert:${jsonPathVersion}"
    testCompile "org.hamcrest:hamcrest-all:${hamcrestVersion}"
    exclude(module: 'hamcrest-core')
}

testCompile "org.powermock:powermock-mockito-release-full:1.6.4"

 // testCompile('org.powermock:powermock-module-junit4:1.6.4')
 // testCompile('org.powermock:powermock-api-mockito:1.6.4' )

}


eclipse {
classpath {
    containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
    containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}

jar { baseName = "trackimo" }

task coverageReport(type: JacocoReport) {

executionData = files("$buildDir/covarageTest/jacocoTest.exec")
classDirectories = files("$buildDir/classes");
sourceDirectories = files("src");

reports {
    xml.enabled false
    csv.enabled false
    html.destination "$buildDir/reports/covarageTest/jacocoHtml"
}

}

test {
jacoco {
    append = true
    destinationFile = file("$buildDir/covarageTest/jacocoTest.exec")
    classDumpFile = file("$buildDir/covarageTest/classpathdumps")

}
finalizedBy tasks.coverageReport
}

task wrapper(type: Wrapper) { gradleVersion = '2.14' }

当我运行以下代码时,会导致以下错误

错误日志:

.19:42:21.368 [main] ERROR o.s.boot.SpringApplication - Application    startup failed 
org.springframework.beans.factory.BeanCreationException: Error     creating bean with name 'springSecurityFilterChain' defined in class path    resource [org/springframework/security/config/annotation/web/configuration/WebSecur     ityConfiguration.class]: Bean instantiation via factory method   failed; nested exception is   org.springframework.beans.BeanInstantiationException: Failed to    instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is     org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
at   org.springframework.beans.factory.support.ConstructorResolver.instantiateU singFactoryMethod(ConstructorResolver.java:599) ~[spring-beans- 4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:347) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:295) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1112) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1101) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at com.trackimo.server.TrackimoServerApplication.main(TrackimoServerApplication.java:15) [main/:na]
Caused by: org.springframework.beans.BeanInstantiationException:    Failed to instantiate [javax.servlet.Filter]: Factory method   'springSecurityFilterChain' threw exception; nested exception is   org.springframework.security.config.annotation.AlreadyBuiltException: This   object has already been built
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 20 common frames omitted
Caused by: org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:44) ~[spring-security-config-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:105) ~[spring-security-config-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$9a87c1cf.CGLIB$springSecurityFilterChain$3(<generated>) ~[spring-security-config-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$9a87c1cf$$FastClassBySpringCGLIB$$5dcb6e03.invoke(<generated>) ~[spring-security-config-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at    org.springframework.security.config.annotation.web.configuration.WebSecuri tyConfiguration$$EnhancerBySpringCGLIB$$9a87c1cf.springSecurityFilterChain (<generated>) ~[spring-security-config-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorIm pl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at  org.springframework.beans.factory.support.SimpleInstantiationStrategy.inst antiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-     4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 21 common frames omitted
:run FAILED

最佳答案

以下重复配置导致了此问题:

http.antMatcher("/api/internal/v1/user/login").csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/internal/v1/user/login").permitAll();

关于java - Spring安全配置: AlreadyBuiltException: This object has already been built,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893985/

相关文章:

java - 创建 Spark SQL 的 StructType : use add method or a constructor?

java - 使用 Spring MVC 提供 Java 模型的 RDF 表示?

java - 按执行顺序列出给定进程的所有任务

java - Thymeleaf 获取没有基本 url 的当前 url

java - SWT单线程问题

java - 嵌套 do while 循环从一个循环跳转到另一个循环

java - 如何在没有请求的情况下获取 Spring session ?

spring - 如何使用gradle创建样板spring-mvc应用程序?

用于长时间运行流程的 Spring SSE

java - 如何解决 "Reached the maximum number of URI tags for http.client.requests"警告?