Tag Archives: spring

How to Solve Springboot Upload Files Error: The field XXX exceeds its maximum permitted size of 1048576 bytes

When uploading a file using springboot, the following error is reported

 ERROR 11136 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field photos exceeds its maximum permitted size of 1048576 bytes.] with root cause

org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field photos exceeds its maximum permitted size of 1048576 bytes.
	at org.apache.tomcat.util.http.fileupload.impl.FileItemStreamImpl$1.raiseError(FileItemStreamImpl.java:114) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at java.io.FilterInputStream.read(FilterInputStream.java:107) ~[na:1.8.0_221]
	at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:291) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.connector.Request.parseParts(Request.java:2922) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.connector.Request.getParts(Request.java:2824) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:122) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1202) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1036) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.9.jar:5.3.9]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.52.jar:9.0.52]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_221]

Error reporting reason:

The upload size of a single file cannot be more than 1MB

The upload size of multiple files cannot be more than 10MB

Simple analysis of the underlying source code of springboot

// I have intercepted parts of both of these classes, so those who are interested can see for themselves

// Configuration class for file upload
public class MultipartProperties {
    private boolean enabled = true;
    private String location;

    // Default individual file size is 1MB
    private DataSize maxFileSize = DataSize.ofMegabytes(1L);
    
    // Default multiple file size is 10MB
    private DataSize maxRequestSize = DataSize.ofMegabytes(10L);
    
    private DataSize fileSizeThreshold = DataSize.ofBytes(0L);
    private boolean resolveLazily = false;
}

// Set file size
public final class DataSize implements Comparable<DataSize>, Serializable {
	/**
	 * The pattern for parsing.
	 */
	private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");

	/**
	 * Bytes per Kilobyte.
	 */
	private static final long BYTES_PER_KB = 1024;

	/**
	 * Bytes per Megabyte.
	 */
	private static final long BYTES_PER_MB = BYTES_PER_KB * 1024;

	/**
	 * Bytes per Gigabyte.
	 */
	private static final long BYTES_PER_GB = BYTES_PER_MB * 1024;

	/**
	 * Bytes per Terabyte.
	 */
	private static final long BYTES_PER_TB = BYTES_PER_GB * 1024;


	private final long bytes;


	/**
	 * Obtain a {@link DataSize} representing the specified number of megabytes.
	 * @param megabytes the number of megabytes, positive or negative
	 * @return a {@link DataSize}
	 */
	public static DataSize ofMegabytes(long megabytes) {
		return new DataSize(Math.multiplyExact(megabytes, BYTES_PER_MB));
	}
}

Solution: you can customize the configuration in the properties or yaml configuration file to modify the maximum upload limit of spring boot file. Here I configure it in yaml

spring:
  mvc: 
  servlet:
    multipart:
      max-file-size: 10MB  		# Set the maximum size of a single file to 10MB
      max-request-size: 100MB # Set multiple file size to 100MB

Error starting ApplicationContext. To display the conditions report re-run your application with ‘de

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled. How to Solve
Error Message:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-10-02 13:18:49.964 ERROR 7280 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field navigationMapper in com.test.littleapp.controller.NavigationController required a bean of type 'com.test.littleapp.mapper.NavigationMapper' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.test.littleapp.mapper.NavigationMapper' in your configuration.

Solution:

Under the main file of spring boot application, add

@MapperScan("Your mapper name")

package com.test.littleapp;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.test.littleapp.mapper")
public class LittleappApplication {
    public static void main(String[] args) {
        SpringApplication.run(LittleappApplication.class, args);
    }
}

springcloud alibaba Integrating nacos reports errors: create config service error!properties=NacosConfigPropertie

Solution:

First, check whether the YML file is configured

spring:    
    cloud:
        nacos:
          discovery:
            server-addr: 127.0.0.1:8848
      application:
        name: gulimall-member

If the configuration is completed, check whether the POM file references the configuration center

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

If so, just comment it out.

Problem reason: when Nacos config is used for unified configuration management, the bootstrap.properties configuration file is used to initialize the context when starting the springboot project.

When using the unified configuration of springcloudconfig, the loading order of spring boot configuration files is bootstrap.properties – & gt; bootstrap.yml -> application.properties -> Application.yml, where bootstrap.properties is configured as the highest priority.

Therefore, an error is reported if the properties file is not found during configuration.

If you need to use the Nacos configuration center, on the premise of referencing the above dependencies, you need to add the bootstrap.properties file in the resource directory, configure the service name, Nacos address and port number, and restart the service.

spring.application.name=gulimall-coupon
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

 

Spring-boot Use dubbo Error: ERROR 8404 o.s.boot.SpringApplication:Application run failed

Error reporting is shown in the figure above

Results after carefully checking the error information, it is found that:

at demo0929.UserServiceApplication.main(UserServiceApplication.java:12) ~[classes/:na]

The format of package scanning configuration is incorrect, as shown in the following figure:

import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@DubboComponentScan(basePackages = {"demo0929.service"})
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class,args);
    }
}

Then delete the cache in the target

[Solved] springmvc:Error creating bean with name ‘org.springframework.cache.interceptor.CacheInterceptor

Error creating bean with name 'org.springframework.cache.interceptor.CacheInterceptor#0’
Speaking of this is a bit of a pitfall, spring configuration file add annotation scan **

<mvc (as long as this is checked again):annotation-driven

** /> After that, idea will automatically add a reference to you, but it adds a reference to xmlns:mvc="http://www.springframework.org/schema/cache", which causes problems. It should be changed to xmlns:mvc=”http://www.springframework.org/schema/mvc”

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘use

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [E:\ProjectTest\IdeaProject\DVillages\target\classes\com\xh\mapper\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\ProjectTest\IdeaProject\DVillages\target\classes\mybatis\mapper\supervise\ComplaintMailbox.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [

Before XML modification of SQL statement:

after modification

the reason is the wrong parametertype

How to Solve error creating bean with name when springboot starts

1, there will be the following start error, at first do not know how to deal with, after a variety of Baidu, found that adding a note on the line
2. This error will also occur

3. You need to add the following comments to run successfully

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

Then run again to run successfully

The most important one is autoconfigurationimportselector.class. With autoconfigurationimportselector, @ enableautoconfiguration can help springboot applications load all qualified @ configuration configurations into the IOC container created and used by the current springboot

The operation results are as follows

The springboot test class reported an error NullPointerException

The test class should be annotated @ runwith (springrunner. Class)
the significance of the annotation is that the test class should use the injected class, such as the class injected by @ Autowired,

With @ runwith (springrunner. Class), these classes can be instantiated into the spring container, and automatic injection can take effect,

Otherwise, just a NullPointerException

@SpringBootTest
@RunWith(SpringRunner.class)
public class AppTest
{
    @Autowired
    private Sender sender;

    @Test
    public void Sendtest(){

        System.out.println(Sender.class+""+sender);
        sender.send();


    }
}

You can still run without @ runwith in the idea because it is recognized as a JUnit running environment in the idea, which is equivalent to a self recognized runwidth environment configuration. But not in other ides. Therefore, in order that your code can run normally in other ides, it is recommended to add @ runwith (springrunner. Class)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘globalTransa

Errors are reported as follows:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘globalTransactionScanner’ defined in class path resource

Error creating bean named “globaltransactionscanner”, which is in classpath resource [COM/Alibaba/cloud/Seata/globaltransactionautoconfiguration. Class]: bean instance via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.seata.spring.annotation.GlobalTransactionScanner]: Factory method ‘globalTransactionScanner’ threw exception; nested exception is io.seata.common.exception.NotSupportYetException: config type can not be null

Failed to instantiate bean through factory method; The nested exception is o.seata.common.exception.notsupportyetexception: the configuration type cannot be null

Three modules: order module + account module + inventory storage module realize the TCC mode of Seata TCC distributed transaction.

Start order to test

Start services in order:

    EurekaSeata ServerEasy Id GeneratorOrder

Failed to start the order project.

Presentation:

Solution:

1. Add global transaction annotation

2. Add transaction group

3. Add two important conf files [key step]

The file.conf file is as follows:

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  # order_tx_group & yml  “tx-service-group: order_tx_group” shoud be the same
  # “seata-server” and  the register name of TC Service should be the same
  # get the url of seata-server in eureka, and register seata-server, set group
  vgroupMapping.order_tx_group = "seata-server"
  #only support when registry.type=file, please don't set multiple addresses
  order_tx_group.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

Registry.conf file:

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "eureka"

  nacos {
    serverAddr = "localhost"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    # application = "default"
    # weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
    password = ""
    cluster = "default"
    timeout = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
    group = "SEATA_GROUP"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

Finally, start successfully!!

Error creating bean with name ‘helloController‘: Injection of autowired dependencies failed;

Error content:
when using the automatic injection of springboot, the configuration file in yaml format is used for injection, but the error is always reported and cannot be injected.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘helloController’: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘name’ in value “${name}”

I searched many posts saying that I should pay attention to the application scanning my folder and corresponding subfolders. Many people step on the pit in this place, but my problem is not here
code

@RestController
public class HelloController {

    @Value(value = "${name}")
    private String name;
    
    @RequestMapping("/hello")
    public String hello(){
        System.out.println(name);
        return "hello Spring Boot !";
    }
}

Add the annotation to read the configuration file on hellocontroller

@PropertySource(value = "classpath:application.yaml")

That solved the problem

[Solved] Spring Boot Project Error: Failed to load property source from

1. There may be a problem with the encoding format of yaml configuration file

All set to UTF-8.

2. Or check whether the writing configured in the file is wrong. For example, the indentation of the next level is less than that of the previous level

The name and weight in the above figure are more than one indentation than the OO in the above figure. Just change the indentation to normal, as shown below