Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 23

0
votes
answers
8 views
+10

Axios不發送授權標頭 - ReactJS

0

我在axios GET請求中設置授權標頭時遇到問題。 我做了很多研究,但沒有找到解決辦法。此外,我檢查了CORS設置,它應該是正常的,並且請求是從郵遞員或預先休息客戶端工作的,所以我不相信這是服務器端的問題。Axios不發送授權標頭 - ReactJS

我與愛可信的請求

export function getUserInfo (userId) { 
    return function (dispatch) { 
    axios.get(`${ROOT_URL}/user/${userId}`, helperMethods.authorizedHeader()) 
    .then(response => { 
     dispatch({type: USER_INFO, payload: response.data.message}); 
    }) 
    .catch(error => { 
     console.log('something went wrong: ', error); 
    }); 
    }; 
} 

Helper方法函數(它返回有效的對象,我調試它)

export function authorizedHeader() { 
    let token = sessionStorage.getItem(TOKEN); 
    if (!token) { 
    token = localStorage.getItem(TOKEN); 
    } 
    return { 
    headers: { 
    'Accept': 'application/json', 
    'Authorization': `${token}` 
    } 
}; 
} 

而且CORS設置:

@Bean 
public CorsFilter corsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
    CorsConfiguration config = new CorsConfiguration(); 
    config.setAllowCredentials(true); 
    config.addAllowedOrigin("*"); 
    config.addAllowedHeader("*"); 
    config.addAllowedMethod("*"); 
    source.registerCorsConfiguration("/**", config); 
    return new CorsFilter(source); 
} 

所以,如果你有任何建議請與我分享。

謝謝

沙发
0
0

最後,我發現了這個問題。問題出在我服務器端的CORS配置上。當請求被觸發時,它首先進入彈簧CORS過濾器,這是拒絕請求,並且它從不觸發我的CORS過濾器。 所以我要設置觸發,類似的東西的順序:

FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
    bean.setOrder(-110); 

這裏是整個更新CORS配置:

@Bean 
public FilterRegistrationBean platformCorsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 

    CorsConfiguration configAutenticacao = new CorsConfiguration(); 
    configAutenticacao.setAllowCredentials(true); 
    configAutenticacao.addAllowedOrigin("*"); 
    configAutenticacao.addAllowedHeader("Authorization"); 
    configAutenticacao.addAllowedHeader("Content-Type"); 
    configAutenticacao.addAllowedHeader("Accept"); 
    configAutenticacao.addAllowedMethod("POST"); 
    configAutenticacao.addAllowedMethod("GET"); 
    configAutenticacao.addAllowedMethod("DELETE"); 
    configAutenticacao.addAllowedMethod("PUT"); 
    configAutenticacao.addAllowedMethod("OPTIONS"); 
    configAutenticacao.setMaxAge(3600L); 
    source.registerCorsConfiguration("/**", configAutenticacao); 

    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
    bean.setOrder(-110); 
    return bean; 
} 
0
votes
answers
6 views
+10

多線程彈簧啓動控制器

1

以下是我的春天控制器之一的代碼。在這個我需要存儲一些數據在多線程postgres數據庫,所以我沒有等到它將數據保存到數據庫,我可以發送響應回到被調用的API。我可以如何實現這一目標?多線程彈簧啓動控制器

//billingLogService.saveBillingLogDetails(Object); 
if (!Util.isNull(personId) && !Util.isNull(personConnectionData)) { 
    return new Callable<Map<Long, PersonConnectionTo>>() { 
     @Override 
     public Map<Long, PersonConnectionTo> call() throws Exception { 
      Map<Long, PersonConnectionTo> connectionTextMap = 
       profileService.getconnectionTextForFocusCompany(focusCompanyId, personId, personConnectionData); 
      return connectionTextMap; 
     } 
    }; 
} 
+0

你可以看看使用Spring的'@ Async'註解。 – CollinD

沙发
0
0

其中一種方法是將整個邏輯(您想在單獨的線程中運行)放到某個服務類的方法中。
然後
1.用@Service或類似的註釋類。
2. @Async
3.使用@EnableAsync
標註方法,這應該足夠了

+0

獲取異常警告9071 --- [cTaskExecutor-2] ohengine.jdbc.spi.SqlExceptionHelper:SQL錯誤:0,SQLState:42883 錯誤9071 --- [cTaskExecutor-2] ohengine.jdbc.spi.SqlExceptionHelper錯誤:運算符不存在:bigint = bytea 提示:沒有運算符匹配給定的名稱和參數類型。您可能需要添加顯式類型轉換。 Position:123 ERROR 9071 --- [cTaskExecutor-2] .a.i.SimpleAsyncUncaughtExceptionHandler:調用異步方法'public void com.equilar.bsp.service.impl.BillingLogServiceImpl.saveConnectionText(java.lang.Long)'時發生意外的錯誤。 – vk1

+0

這與你的代碼有些相關,ant完全與運行在單獨的線程中有關 – pvpkiran

0
votes
answers
9 views
+10

硬化SpringBoot的嵌入式Tomcat

0

Tomcat和SpringBoot的新功能硬化SpringBoot的嵌入式Tomcat

我需要確保SpringBoot中的嵌入式Tomcat硬化到一定水平。我正在使用this CIS doc(您將需要dl pdf)作爲我們可能想要做的清單。但是,該文檔面向「正常安裝」的Tomcat。例如,我指示更新$ CATALINA_HOME中找到的文件。

SpringBoot提供了一種方法來完全控制/訪問它的嵌入式Tomcat嗎?如果沒有,是否可以合理地從SpringBoot外部配置Tomcat,然後用我自己的默認SpringBoot Tomcat替代?我也接受其他解決方案。

+0

與其盲目地跟蹤文檔,如果您甚至需要它,並且該文檔中的所有內容甚至適用於嵌入式tomcat! –

沙发
0
1

如果你必須遵循該指南,最簡單的方法就是將WAR引導應用打包爲WAR並將其部署到常規Tomcat服務器中。本指南解釋如何package an app as a war

當你開始打開它時,Tomcat是一個非常複雜的軟件。您可以編寫可以訪問Tomcat配置並自行設置配置設置的java代碼。另外,tomcat被分解成許多組件,其中一些需要修改的文件可能適用於不屬於spring boot的嵌入式tomcat的組件。

您可以加強spring啓動應用程序,但如果您按照指南進行操作,則工作會更容易。

+0

是否有關於使用嵌入式Tomcat強化spring引導應用的特定文檔? – AR3Y35

0
votes
answers
11 views
+10

SpringBootApplication無法解析爲Spring工具套件和maven中的類型錯誤

1

我在spring工具套件中創建了maven項目。我創建了具有所需依賴性的pom.xml,但由於「SpringBootApplication無法解析爲類型」而面臨錯誤。 我嘗試了幾個解決方案,如Maven - >更新項目...,清潔項目,刪除Maven(.m2)的本地存儲庫目錄等...我也嘗試創建另一個Maven項目,但仍然是相同的錯誤。SpringBootApplication無法解析爲Spring工具套件和maven中的類型錯誤

我覺得這是eclipse的spring工具套件與maven的問題。 是否有任何解決方案像通過日食或其他任何補丁? 在此先感謝!

的pom.xml如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>io.javabrains.springbootquickstart</groupId> 
    <artifactId>cource.api</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>Java Brains Cource API</name> 
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent --> 
    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.8.RELEASE</version> 
    </parent> 
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent --> 
    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-parent</artifactId> 
      <version>1.5.8.RELEASE</version> 
      <type>pom</type> 
     </dependency> 
    </dependencies> 
    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
    <properties> 
     <java.version>1.8</java.version> 
    </properties> 
</project> 
+0

你是否已經嘗試命令mvn乾淨安裝從命令行下你的項目? –

+0

'......不能解析爲類型「表示導入缺失或無法解析。在後一種情況下,「導入...無法解決」是您應該查看的錯誤。你有這樣的錯誤嗎? – howlger

沙发
0
1

您還沒有添加正確的依賴關係。

您應該添加

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter</artifactId> 
    </dependency> 

的依賴(在<dependencies>)代替spring-boot-starter-parent。 父只定義了版本,但實際上並沒有添加任何依賴項(您在Maven中將其用作<parent>)。

如果您有測試,還可以添加spring-boot-starter-test

我也建議(在文件 - >新建 - >其他>春季啓動項目也可從STS)使用https://start.spring.io/生成一個工作彈簧引導基地項目。

+0

謝謝! 我明白這個問題,這是因爲提到的helospark的不正確的依賴。 – Ameet

板凳
0
0
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
<modelVersion>4.0.0</modelVersion> 
<groupId>io.javabrains.springbootquickstart</groupId> 
<artifactId>cource.api</artifactId> 
<version>0.0.1-SNAPSHOT</version> 
<name>Java Brains Cource API</name> 

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.5.8.RELEASE</version> 
</parent> 

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-autoconfigure</artifactId> 
    </dependency> 
</dependencies> 

<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 

<properties> 
    <java.version>1.8</java.version> 
</properties> 

</project> 

將其複製/粘貼到您的POM.xml中。更新Maven項目,它將獲取所需的JAR。

0
votes
answers
27 views
+10

在依賴jar中的異步註釋,沒有啓動一個新線程

2

我有一個依賴jar的類,它有一個用Spring @Async註解的方法,我期望這個方法應該在另一個線程中異步執行。在依賴jar中的異步註釋,沒有啓動一個新線程

使用這個類,我在我的父項目中創建一個bean並將它連接到我的類,該類有@Service註釋。在那個類中,我調用了一個有註解的方法,但正如我所說的,該方法不會在另一個線程中執行。

我該如何做到這一點?

這是代碼。

這是我的接口類:

public interface RequestLoggerService { 

    @Async 
    void log(HttpServletRequest request, String serviceName, String requestIdentifier, String message, boolean successful); 
} 

這是實現類:

public class RequestLoggerServiceImpl implements RequestLoggerService { 

    private static Logger logger = Logger.getLogger(RequestLoggerServiceImpl.class); 

    private RequestLoggerDao requestLogger; 

    @Override 
    public void log(HttpServletRequest request, String serviceName, String requestIdentifier, String message, boolean successful) { 
     logRequest(request, serviceName, request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1), requestIdentifier, message, successful); 
    } 
} 

這兩個類都裝在一個罐子是在我父項目中使用的依賴。我使用這個類來創建父項目一個bean:

<bean id="requestLoggerService" class="com.xyz.service.RequestLoggerServiceImpl"> 
    <property name="requestLogger" ref="requestLoggerDao" /> 
</bean> 

而且這個bean然後自動連線在我@Controller註解類:

public class ActionsController { 

    @Autowired 
    private RequestLoggerService requestLogger; 
} 
+0

代碼必須有問題。發表它。 –

+2

你使用XML配置還是'@ Configuration'/spring boot?如果是後者,那麼您可能需要添加'@ EnableAsync'註釋,請參閱https://spring.io/guides/gs/async-method/請參閱http://stackoverflow.com/questions/31401640/spring-xml - 對等的啓用同步的XML版本 – BretC

+0

嗯,我混了一下,但我有@EnableAsync批註...當我有我的父項目中的異步方法的類,然後一切工作正常,儘快我將它移動到jar中,並從該jar中的類初始化bean,它不起作用... – dplesa

沙发
0
0

我跟着@BretC指令並找到了解決辦法。問題在於我通過XML配置實例化了RequestLoggerService bean,但使用註釋@EnableAsync來啓用@Async註釋發現。

無論如何,我需要使用註解驅動的bean創建,或者在XML配置中啓用異步任務。

0
votes
answers
14 views
+10

如何在Spring Boot可執行文件中使用提供的jmagick庫?

0

我提供的位於/usr/share/java/jmagick-6.6.9.jar的jmagick庫。如何在Spring Boot可執行文件中使用提供的jmagick庫?

後啓動應用程序,我有錯誤:

java.lang.ClassNotFoundException: magick.MagickException

gradle.build已經jmagick:

provided group: 'jmagick', name: 'jmagick', version: '6.6.9' 

和application.properties有loader.path:

loader.path=jmagick-6.6.9.jar!/usr/share/java 
沙发
0
0

解決方案

集 'ZIP' 上的build.gradle佈局:

springBoot { 
    executable = true 
    layout = 'ZIP' 
} 

創建loader.properties:

loader.path=/usr/share/java/jmagick-6.6.9.jar 
0
votes
answers
3 views
+10

Trying to use Spring Boot REST to Read JSON String from POST

Am using the latest version of Spring Boot to read in a sample JSON via Restful Web Service...

Here's my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"       
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/maven-v4_0_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>myservice</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
        </dependency>
        <dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Here's my web service code:

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/myservice")
public class BaseService {  

    @RequestMapping(value="/process", method = RequestMethod.POST)
    public void process(@RequestBody String payload) throws Exception {
        System.out.println(payload);
    }
}

When I invoke it using the following command:

curl -H "Accept: application/json" -H "Content-type: application/json" 
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

I get this error message:

{"timestamp":1427515733546,"status":400,
 "error":"Bad Request",

"exception":
"org.springframework.http.converter.HttpMessageNotReadableException","
 message":
 "Could not read JSON: Can not deserialize instance of java.lang.String
  out of START_OBJECT token
 at 

 [Source: java.io.PushbackInputStream@8252f; line: 1, column: 1]; 
  nested    exception is com.fasterxml.jackson.databind.JsonMappingException:
  Can not deserialize instance of java.lang.String out of START_OBJECT token
    
  at [Source: java.io.PushbackInputStream@8252f; line: 1, column: 1]",
  "path":"/myservice/process"

The only thing I am trying to do is pass in some valid JSON (as a string via curl) and to see if the String payload enters the process method as {"name":"value"}

What am I possibly doing wrong?

Thank you for taking the time to read this...

0
votes
answers
10 views
+10

我可以在我的Spring啓動應用程序中使用Spring集成模塊嗎?

1

我正在爲我的ftp服務器製作一個filedownload endpoint。我發現Spring引導中有一個Spring引導集成啓動模塊,但該模塊不包含像DefaultFtpSessionFactory這樣的類。我在網上讀過,有其他模塊可用,如Spring集成http和Spring集成ftp。但是,這些不是彈簧引導模塊。無論如何將這些模塊包含在我的POM中保存是否存在?或者,我首先使用Spring引導啓動器集成?我可以在我的Spring啓動應用程序中使用Spring集成模塊嗎?

我在這個例子中看到:https://blog.pavelsklenar.com/spring-integration-sftp-upload-example/作者在Spring Integration 4.3.8常規Spring旁邊使用spring boot。他確實說這些是由Spring啓動管理的,但我不完全確定他的意思。

任何人都可以告訴我,我應該包括什麼模塊,如果我想使下載功能?謝謝

沙发
0
3

由於應用程序不太可能需要所有Spring集成模塊(ftp,sftp,http,mqtt等),因此初始程序僅在類路徑中包含核心和java dsl jar(在Spring Integration 5.0 ,DSL是內置的,因此boot 2.0只包含核心jar)。

否則,你最終會在類路徑上有許多不需要的jar。

所以,是的,你必須手動添加所需要的依賴......

<dependency> 
    <groupId>org.springframework.integration</groupId> 
    <artifactId>spring-integration-ftp</artifactId> 
</dependency> 

請注意,您需要<version/> - 啓動會處理這件事對你和正確的把版本對應於核心。

模塊本身會帶來任何他們需要的附加傳遞依賴。所以你只需要添加頂級模塊到你的POM。

28
votes
answers
5 views
+10

How to disable Hibernate validation in a Spring Boot project

I have a spring boot project that has a CrudRepository, an Entity and a Controller. I am basically trying to persist an entity based on the data passed to the Controller.

To do this, I am using spring-boot-starter-jpa. My Entity is annotated with JSR-303 annotations, which are checked in the controller before the data gets passed to the CrudRepository for persistence.

Controller method:

@RequestMapping(value = "users", method = { RequestMethod.POST })
public SuccessfulResponse<User> addUser(@Valid @RequestBody User user, BindingResult validation) {
    if (validation.hasErrors()) {
        throw new ValidationException(validation);
    }
    User saved = this.users.save(user);
    return new SuccessfulResponse<User>(saved);
}

Entity:

@Entity /* JPA */
public class User {

   @Id /* JPA */
   @Column(name="email_address", nullable=false, length=255) /* JPA */
   @UserUnique
   private String emailAddress;

}

The cause of my issues is the UserUnique annotation. Its validator looks like this:

public class UserUniqueValidator implements ConstraintValidator<UserUnique, String> {

   private UserRepository users;

   @Autowired
   public UserUniqueValidator(UserRepository users) {
       this.users = users;
   }

   @Override
   public void initialize(UserUnique annotation) {}

   @Override
   public boolean isValid(String value, ConstraintValidatorContext context) {
       return users.findOne(value) == null;
   }
}

What seems to be happening is, the validation is getting run twice. Once in the controller via the @Valid annotation, and once when Hibernate tries to persist the object. However, when Hibernate tries to persist the object, it throws:

javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: class test.UserUniqueValidator`

This seems to be because its not spring-aware and cant inject the dependency into the constructor. So, what I want to do is disable Hibernate validation completely (as its redundant and already happening in the controller).

There seems to be a property called javax.persistence.validation.mode which you can set to none. However, I cant for the life of me figure out where to set it in a code-based configuration.

I realise there are questions like JSR-303 dependency injection and Hibernate but these are all using xml config and manually configuring parts of the persistence layer.

What I want to do is "post-configure" the required parts of the persistence layer that Spring Boot creates for me because if I define my own then I am no longer leveraging Spring Boot's auto configuration. Can anyone help me determine if 1) this is possible and 2) which parts do I need to configure and how?

Thanks!

up vote 28 down vote accepted favorite
沙发
+280
+50

作為[M. Deinum]在我原帖的評論中提到,解決方案是設置:

  spring.jpa.properties.javax.persistence.validation.mode = none   

application.properties 文件中。

此外,此行為是此處描述(很容易錯過,因為沒有提供示例)。

0
votes
answers
29 views
+10

試圖重現彈簧安全OAuth2Login示例

0

我想學習一些Spring Security時不斷出現錯誤。但是我有麻煩來通過Auth2/OpenId Connect來保護我的網頁。我嘗試重現Spring Security Reference OAuth2 Client的示例。試圖重現彈簧安全OAuth2Login示例

但我已經堅持在開始運行該項目。我使用maven而不是gradle作爲構建工具。 如果我運行從例子中的測試中,我不斷收到一個例外,它說的是,應用程序上下文無法加載

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available: expected at least 1 bean which qualifies as autowire candidate. 

完整的異常

java.lang.IllegalStateException: Failed to load ApplicationContext 
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] 
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] 
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] 
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] 
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] 
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na] 
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na] 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na] 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na] 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na] 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na] 
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'OAuth2LoginApplicationTests.SpringBootApplicationTestConfig': Unsatisfied dependency expressed through field 'clientRegistrationRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] 
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] 
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE] 
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.8.RELEASE.jar:1.5.8.RELEASE] 
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
... 25 common frames omitted 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE] 
... 43 common frames omitted 

然後即時得到一個奇怪的編譯使用示例中完全相同的代碼時出現錯誤。

即使在HttpSecuritydocumentation中,該方法似乎也不存在。我對這個問題非常困惑。我是否導入錯誤的依賴關係?

OAuth2LoginApplicationTests.java線356?386

@Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .anyRequest().authenticated() 
       .and() 
      .oauth2Login()  <-- this method does not exist 
       .tokenEndpoint() 
        .accessTokenResponseClient(this.mockAccessTokenResponseClient()) 
        .and() 
       .userInfoEndpoint() 
        .userService(this.mockUserService()); 
    } 

的pom.xml依賴

<repositories> 
    <repository> 
     <id>spring-milestones</id> 
     <name>Spring Milestones</name> 
     <url>https://repo.spring.io/libs-milestone</url> 
     <snapshots> 
      <enabled>false</enabled> 
     </snapshots> 
    </repository> 
</repositories> 

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-security</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-test</artifactId> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.security</groupId> 
     <artifactId>spring-security-web</artifactId> 
    </dependency> 

    <dependency> 
     <groupId>org.springframework.security</groupId> 
     <artifactId>spring-security-config</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.security</groupId> 
     <artifactId>spring-security-test</artifactId> 
     <scope>test</scope> 
    </dependency> 

    <!-- OAuth2 for clients --> 
    <dependency> 
     <groupId>org.springframework.security.oauth</groupId> 
     <artifactId>spring-security-oauth2</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.security</groupId> 
     <artifactId>spring-security-oauth2-client</artifactId> 
     <version>5.0.0.RC1</version> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.security</groupId> 
     <artifactId>spring-security-oauth2-jose</artifactId> 
     <version>5.0.0.RC1</version> 
    </dependency> 

    <dependency> 
     <groupId>net.sourceforge.htmlunit</groupId> 
     <artifactId>htmlunit</artifactId> 
     <scope>test</scope> 
    </dependency> 

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webflux --> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-webflux</artifactId> 
     <version>5.0.1.RELEASE</version> 
    </dependency> 

    <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 --> 
    <dependency> 
     <groupId>org.thymeleaf.extras</groupId> 
     <artifactId>thymeleaf-extras-springsecurity4</artifactId> 
    </dependency> 

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-thymeleaf</artifactId> 
    </dependency> 

    <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-core --> 
    <dependency> 
     <groupId>io.projectreactor</groupId> 
     <artifactId>reactor-core</artifactId> 
     <version>3.1.2.RELEASE</version> 
    </dependency> 
    <dependency> 
     <groupId>io.projectreactor.ipc</groupId> 
     <artifactId>reactor-netty</artifactId> 
     <version>0.7.2.RELEASE</version> 
    </dependency> 

    <dependency> 
     <groupId>com.jayway.jsonpath</groupId> 
     <artifactId>json-path</artifactId> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.projectlombok</groupId> 
     <artifactId>lombok</artifactId> 
     <scope>provided</scope> 
    </dependency> 

    <dependency> 
     <groupId>com.google.code.findbugs</groupId> 
     <artifactId>jsr305</artifactId> 
     <version>3.0.1</version> 
     <scope>provided</scope> 
    </dependency> 
</dependencies> 

我是否錯過任何依賴關係或有錯誤的版本?如果我用gradle導入完整的項目,一切正常。

沙发
0
0

我發現了爲什麼會出現異常。我使用了錯誤版本作爲spring boot parent。

的例子使用的春天啓動的里程碑版本2.0.0.M6而不是最新發布版本1.5.8.RELEASE

我只是不得不改變

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.5.8.RELEASE</version> 
</parent> 

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>2.0.0.M6</version> 
</parent> 

注意塔t這是不是的發佈版!