小编Joã*_*ias的帖子

Swagger 2 问题 - Spring Boot

我正在使用教程,一切都工作正常,直到我开始处理 swagger 2 依赖项。\n我现在想知道是否有办法解决这个问题。

\n

Swagger配置:

\n
package com.animes.apirest.config;\n\nimport springfox.documentation.swagger2.annotations.EnableSwagger2;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\nimport springfox.documentation.builders.RequestHandlerSelectors;\nimport springfox.documentation.service.ApiInfo;\nimport springfox.documentation.service.Contact;\nimport springfox.documentation.service.VendorExtension;\nimport springfox.documentation.spi.DocumentationType;\nimport springfox.documentation.spring.web.plugins.Docket;\n\n\nimport static springfox.documentation.builders.PathSelectors.regex;\n\nimport java.util.ArrayList;\n\n@Configuration\n@EnableSwagger2\npublic class SwaggerConfig {\n    \n    @Bean\n    public Docket atividadeApi() {\n        return new Docket(DocumentationType.SWAGGER_2)\n                .select()\n                .apis(RequestHandlerSelectors.basePackage("com.atividades.apirest"))\n                .paths(regex("/api.*"))\n                .build()\n                .apiInfo(metaInfo());\n    }\n\n    private ApiInfo metaInfo() {\n\n        ApiInfo apiInfo = new ApiInfo(\n                "Atividades API REST",\n                "API REST de cadastro de atividades.",\n                "1.0",\n                "Terms of Service",\n                new Contact("Jo\xc3\xa3o VR", "www.una.br/",\n                        " "),\n                "Apache License Version 2.0",\n                "https://www.apache.org/licesen.html", new ArrayList<VendorExtension>()\n        );\n\n        return apiInfo;\n    }\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

pom.xml: …

java spring jpa spring-boot

19
推荐指数
4
解决办法
8万
查看次数

如何使用 kotlin 中列表对象的属性创建列表

假设有一个Person具有属性的类name,并且age有一个persons包含 n 个 person 对象的列表。persons除此之外,还有其他更有效的方法从列表中创建年龄列表吗:

val age_list= ArrayList<Int>()
for(person in persons){
    age_list.add(person.getAge())
}
Run Code Online (Sandbox Code Playgroud)

kotlin

11
推荐指数
1
解决办法
1万
查看次数

引起原因:java.lang.ClassNotFoundException:org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata

如何修复这个错误?

就这个:

引起原因:java.lang.ClassNotFoundException:org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata

这是我的 pom.xml 文件

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.5.4</version>
   <relativePath/>
</parent>
<groupId>io.x</groupId>
<artifactId>eureka-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-server</name>
<description>Eureka server</description>
<properties>
   <java.version>16</java.version></docker.artifact.version>
   <spring-cloud-starter-eureka-server.version>1.4.7.RELEASE</spring-cloud-starter-eureka-server.version>
</properties>
<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter</artifactId>
   </dependency>

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

   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-eureka-server</artifactId>
       <version>${spring-cloud-starter-eureka-server.version}</version>
   </dependency>
</dependencies>
<dependencyManagement>
   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Hoxton.SR12</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
   </dependencies>
</dependencyManagement>
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-cloud netflix-eureka

9
推荐指数
1
解决办法
3万
查看次数

调用不存在的端点时收到 403 而不是 404

这是 Spring Security 配置的典型部分:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().and().cors().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.authorizeRequests().antMatchers("/login", "/api/v1/auth/**").permitAll();
    http.authorizeRequests().anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)

我有一个问题http.authorizeRequests().anyRequest().authenticated()

添加后,当我调用不存在的端点时,例如:GET: /api/v1/not-existing,我收到403而不是预期的404响应。

我想保护我的所有资源,但我想在调用不存在的资源时得到 404。

我该如何修复它?

java authentication spring spring-security

8
推荐指数
1
解决办法
2994
查看次数

Swagger 2 问题 spring Boot

我在 Spring Boot 中面临 Swagger 集成问题。查看代码和错误片段。

------------------POM--------------------

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

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-bean-validators</artifactId>
    <version>${swagger.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

-----------------应用类--------------

@SpringBootApplication
@EnableSwagger2
public class ProducerApplication {

  public static void main(String[] args) {
    SpringApplication.run(ServletPocProducerApplication.class, args);
  }
  
  @Bean 
  public Docket api() { 
    return new Docket(DocumentationType.SWAGGER_2)
      .select() 
      .apis(RequestHandlerSelectors.any())
      .paths(PathSelectors.any())
      .build();
  }
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪

org.springframework.context.ApplicationContextException: Failed to start bean 
'documentationPluginsBootstrapper'; nested exception is 
 java.lang.NullPointerException: Cannot invoke 
"org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" 
because the return value of 
"springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.docume 
ntation.RequestHandler)" is null
   at …
Run Code Online (Sandbox Code Playgroud)

java swagger-ui spring-boot swagger-2.0

7
推荐指数
3
解决办法
2万
查看次数

Java 8 可选过滤器(仅当存在时)

null我有一个可为空的对象,如果该对象不满足且不满足条件,我将尝试抛出异常。

我尝试用以下方法Optional

Optional.ofNullable(nullableObject)
    .filter(object -> "A".equals(object.getStatus()))
    .orElseThrow(() -> new BusinessUncheckedException("exception message"));
Run Code Online (Sandbox Code Playgroud)

当对象不是 时null,它会按我想要的方式工作,但否则,它也会引发异常(我不希望这样)。

有一种方法可以做到这一点,Optional或者有其他方法不使用if object != null

java java-8 option-type

6
推荐指数
1
解决办法
4190
查看次数

如何使用 UriBuilder 构建 URI,而不单独指定方案、主机?

参考:org.springframework.web.util.UriBuilder

我正在用来UriBuilder为端点构建 URI

final String response = myWebClient.get()
   .uri(uriBuilder -> uriBuilder.scheme("https").path("example.com/mypage").path("/{id}.xml").build(id))
   .header(AUTHORIZATION, getAuthorizationHeaderValue(username, password))
   .accept(MediaType.TEXT_XML)
   .retrieve()
   .bodyToMono(String.class)
   .block();
Run Code Online (Sandbox Code Playgroud)

但是,我已经在字符串变量中获得了值https://example.com/mypage(从数据库中获取)。我可以直接使用这个字符串而不是单独指定方案和路径/主机吗?现在我正在手动将主字符串分成单独的部分。

uri uribuilder spring-boot spring-webflux spring-webclient

5
推荐指数
1
解决办法
1万
查看次数

server.servlet.contextPath 与 spring.mvc.servlet.path

考虑下面的代码,

@RestController
@RequestMapping("/v1")
class Controller {

}
Run Code Online (Sandbox Code Playgroud)

我应该做的是,删除 @RequestMapping并通过application.properties配置路径。

我发现有两种方法可以实现这一目标,

spring.mvc.servlet.path=/v1
Run Code Online (Sandbox Code Playgroud)

server.servlet.contextPath=/v1
Run Code Online (Sandbox Code Playgroud)

但是它们有什么不同,因为我没有注意到这两种配置有任何区别?哪一个最适合我想要实现的目标?

spring spring-boot

4
推荐指数
1
解决办法
5892
查看次数

orElseGet 在可选&lt;List&lt;Entity&gt;&gt; 的情况下如何工作

我有一个类的可选列表,即:Optional<List<MyEntity>> opListEntity

我需要将所有映射MyEntityMyEntityDto可选存在时。如果Optional为空,我将返回一个空的ArrayList


方法 1(非功能性):

注意:myEntityMapper是一个映射器类的对象,它映射MyEntityMyEntityDto.

List<MyEntityDto> res;
if (opListEntity.isPresent()) {
       res = opListEntity.get().stream()
            .map(myEntityMapper::entityToDto)
            .collect(Collectors.toList());
} else {
       res = new ArrayList<>();
}
Run Code Online (Sandbox Code Playgroud)

这种方法很好,但IntelliJ建议将其转换为函数式表达式。我让 IntelliJ 进行转换,这就是我得到的结果:

方法2(函数表达式):

List<MyEntityDto> res = opListEntity.map(myEntities -> myEntities.stream()
            .map(myEntityMapper::entityToDto)
            .collect(Collectors.toList()))
     .orElseGet(ArrayList::new);
Run Code Online (Sandbox Code Playgroud)

我不明白的是,在方法 2 @ 第 1 行中,为什么会有地图?

让我再解释一下。请参阅第三种方法:

方法三:

List<CustomerAddressEntity> myEntities = opListEntity
        .orElseGet(ArrayList::new);
List<MyEntityDto> res = myEntities.stream()
        .map(myEntityMapper::entityToDto)
        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

方法 3 工作正常,但如果我尝试将方法 3 转换为方法 4,则不起作用。

方法四:

List<MyEntityDto> res …
Run Code Online (Sandbox Code Playgroud)

java functional-programming java-stream

3
推荐指数
1
解决办法
179
查看次数

Spring Boot 服务层:单元测试还是集成测试?

我有一个服务:

@Service
@Transactional
@RequiredArgsConstructor
public class BookService {

    private final BookRepository bookRepository;

    public Book findOne(Long id) {
        return bookRepository.findById(id).orElse(null);
    }

    public Book getOne(Long id) {
        return bookRepository.findById(id)
                .orElseThrow(() -> new BadRequestAlertException("entity-not-found", ("Entity with id: " + id + " not found!")));
    }

    public List<Book> getAll() {
        return bookRepository.findAll();
    }

    public Book save(Book book) {
        return bookRepository.save(book);
    }

}
Run Code Online (Sandbox Code Playgroud)

我已经为数据库(BookRepository)和控制器层(使用 BookService 的 BookController)编写了集成测试。我在任何地方都找不到服务层集成测试的示例。如果我正确编写单元测试,是否有为其编写集成测试的用例?据我所知(这不是规则,而是常见的用例):

  • 控制器 - 集成测试
  • 服务-单元测试
  • 存储库 - 集成测试

java unit-testing spring-boot

2
推荐指数
1
解决办法
2905
查看次数