标签: spring-boot

如何在springboot中添加条件过滤器

我在运行的 Spring Boot 应用程序中有不同的过滤器。我想根据条件跳过一个过滤器来运行少数 api。我可以通过在 doFilterInternal 中添加条件来做到这一点。这里是过滤器的代码:


class ConditionalFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
    HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
    if (!condition) {
        filterChain.doFilter(request, httpResponse);
    } else {
        someFilterLogic();
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?

spring-boot

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

更新 Thymeleaf 中的内容而不重新加载整个页面

我想更新 div“输出”的内容而不重新加载整个页面。当用户输入内容并点击运行按钮时,服务器将在 div“输出”上输出评估结果。但以下代码仅将 div“输出”放在浏览器上。另一页也不见了。我做错了什么?

\n
<body>\n    <div class="container mx-auto">\n        <div th:insert="fragments/body :: navigation (true, ${spieler.name}, ${spieler.punkte}, ${spieler.level})"></div>\n    \n        <div class="d-flex justify-content-center">\n            <label class="text-center mt-4" id="thetext">Du liebst Abenteuer und m\xc3\xb6chte endlich reisen.<br>\n                Du hast ein bisschen Geld und das reicht f\xc3\xbcr ein Ticket zur n\xc3\xa4chsten Insel.<br>\n                Ungl\xc3\xbccklicherweise ist dein Schiff in einem Sturm gesunken. <br>\n                Du hat gl\xc3\xbcck, an einen Strand zu landen. <br><br>\n                Jetzt musst du die Herausforderungen mit deinen SQL-Kenntnissen meistern.<br>\n                Je schneller du die Probleme l\xc3\xb6st, desto besser …
Run Code Online (Sandbox Code Playgroud)

javascript spring-mvc thymeleaf spring-boot

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

错误:关系xxx的列“id”中的空值违反了非空约束 - Spring Data JPA

我有一个关于 Spring JPA 的 @GenerateValue 注释的问题。

这是我的课:

@Entity
@NoArgsConstructor
@Getter
@Setter
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private Double price;
    private Integer quantity;

    @ManyToOne
    private Category category;

    @ManyToOne
    private Manufacturer manufacturer;



    public Product(String name, Double price, Integer quantity, Category category, Manufacturer manufacturer) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.category = category;
        this.manufacturer = manufacturer;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加新产品时,出现此错误:

2021-12-06 18:03:02.013 ERROR 3720 --- [nio-9090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value …
Run Code Online (Sandbox Code Playgroud)

java postgresql spring-data spring-data-jpa spring-boot

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

通过环境变量覆盖 Spring Boot yaml 属性

使用 Spring Boot 2.6.1,如果我有一个application.properties如下所示的文件:

spring.datasource.url="jdbc://blahblah"
Run Code Online (Sandbox Code Playgroud)

我可以在运行时使用名为 的环境变量覆盖该值spring.datasource.url,并且我的应用程序将连接到环境变量中指定的数据库。

但是,如果我有一个等效的application.yaml文件,那么以这种方式指定环境变量似乎没有效果。

spring:
  datasource:
    url: "jdbc://localhost..."
Run Code Online (Sandbox Code Playgroud)

但是,如果我将环境变量重命名为SPRING_DATASOURCE_URL,覆盖将再次起作用。这在其他属性中似乎也是一致的(不仅仅是数据源 URL)。

浏览文档,并不清楚为什么会出现这种情况,除了 yaml 配置似乎通常与“正常”属性文件的处理方式略有不同。

这种行为是预期的吗?

yaml properties-file spring-boot

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

类 java.util.LinkedHashMap 无法转换为类 [...]

我正在向 WooCommerce API 发出 GET 请求以获取订单,我的想法是从响应中获取一些数据并将其插入到本地数据库中。我测试了该请求,一切正常。所以我继续使用 QuickType 来创建与响应相对应的类,这样我就有办法保存它并将其插入数据库。问题如下,如果我注释掉“for”语句,就没有问题了。但在使用它获取答案的值并将其插入数据库时​​,出现此错误:class java.util.LinkedHashMap无法转换为class [name of my class]。而且:[我的类]位于加载器org.springframework.boot.devtools.restart.classloader.RestartClassLoader的未命名模块中。你能帮我找到解决这个问题的方法吗?这是代码:

@GetMapping("/ordenes")
    public List<WcOrden> getOrdenes() {

        List<WcOrden> ordenes = (List<WcOrden>) wc.getAll(EndpointBaseType.ORDERS.getValue(), params);
        for (WcOrden orden : ordenes) {
            log.debug("This is an order");
        }
        return ordenes;
    }
Run Code Online (Sandbox Code Playgroud)

java spring jackson spring-boot

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

如何检查插件“io.spring.dependency-management”管理哪些库

所以...这是场景。

假设我正在尝试添加到library A文件build.gradle

我想知道 的版本是否library A由插件管理io.spring.dependency-management

我怎样才能做到这一点?

我没有提供特定的库,因为特定库的答案不是我正在寻找的

先感谢您!

我的源代码

spring gradle build.gradle spring-boot

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

Spring Data JPA的查询方法如何生成查询?

当在Spring Data JPA的特定规则下创建一个方法时,就会创建一个调用相应查询的方法。

例如,

public interface CustomerJpaRepository implements JpaRepository<Customer, Long>{

    public List<Customer> findByName(String name);
}
Run Code Online (Sandbox Code Playgroud)

findByName() 生成类似于下面的查询。

select * from Customer where name = name;
Run Code Online (Sandbox Code Playgroud)

我对这个原理很好奇。准确地说,我很好奇解析此方法并将其转换为查询的代码。

我查看了实现JpaRepository的SimpleJpaRepository类的代码,但找不到线索。(当然,也有可能是我没找到)。

综上所述,当在 JpaRepository 中声明一个由特定单词组成的方法时,我很好奇内部实际执行这个方法的代码。更具体地说,我想看看使该方法起作用的代码。

如果内部没有代码可以做到这一点(我个人怀疑这可能......),我想知道它是如何详细实现的,如果有解释原理或内部流程的链接或材料,请分享相关参考。

java hibernate jpa spring-data-jpa spring-boot

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

Spring boot Java堆空间用于下载大文件

我正在尝试编写一个 REST api 来允许用户在 Spring boot 上下载大文件(即 > 2GB)。我遇到了“Java Heap outOfMemoryException”。我尝试对问题进行分类,我发现 HttpServetResponse 对象的类型为:ContentCachingResponseWrapper。此类缓存写入输出流的所有内容,当缓存的数据大小变为 258MB 左右时,我会收到 OutOfMemoryException。为什么是 248 MB,因为 JVM 有 256 MB 堆内存。

ContentCachingResponseWrapper 中默认的flushBuffer()方法是空的。如果我尝试调用 copyBodyToResponse()(用于将数据从缓存复制到流),它工作正常,但它也会关闭流。这导致仅将第一块数据发送到客户端。

有什么建议 ?

public void myDownloader(HttpServletRequest request, HttpServletResponse response) {
             //response.getClass() is: ContentCachingResponseWrapper  
             byte[] buffer = new byte[1048576];  // 1 MB Chunks
             FileInputStream inputStream = new FileInputStream(PATH_TO_SOME_VALID_FILE);
             int bytesRead= 0;
             ServletOutputStream outputStream = response.getOutputStream();

             while ((bytesRead = inputStream.read(buffer)) != -1) {              
                 outputStream.write(buffer, 0, bytesRead);
                 outputStream.flush();
                 response.flushBuffer();
               } 
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Caused by: java.lang.OutOfMemoryError: Java heap space …
Run Code Online (Sandbox Code Playgroud)

java spring-boot

4
推荐指数
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
查看次数

如何在Spring Boot应用程序中使用Spring事务配置kafka事务管理器

我在 Spring Boot 应用程序中使用 Kafka。我想在一笔交易中执行操作,如下所示。

listen(){
 produce()
 saveInDb()
} 
Run Code Online (Sandbox Code Playgroud)

operation(){
 saveInDB()
 produce()
}
Run Code Online (Sandbox Code Playgroud)

我已经使用以下配置启用了 Kafka 事务

spring:
  kafka:
    bootstrap-servers: localhost:19092,localhost:29092,localhost:39092
    producer:
      transaction-id-prefix: tx-
    consumer:
      enable-auto-commit: false
      isolation-level: read_committed
Run Code Online (Sandbox Code Playgroud)

并使用此配置

    @Bean
    public ProducerFactory<String, Object> producerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        DefaultKafkaProducerFactory<String, Object> factory = new DefaultKafkaProducerFactory<>(props);
        factory.setTransactionIdPrefix("tx-");
        return factory;
    }

    @Bean
    public KafkaTransactionManager kafkaTransactionManager() {
        KafkaTransactionManager manager = new KafkaTransactionManager(producerFactory());
        return manager;
    }
    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory()); …
Run Code Online (Sandbox Code Playgroud)

java apache-kafka spring-boot spring-kafka

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