Tag Archives: springboot

NoClassDefFoundError: org.springframework.validation.annotation.ValidationAnnotationUtils

After the recent project upgrade, I reported this error inexplicably. A colleague just met it and helped to solve it. Record it

First of all, this class is in the spinning context package. Just upgrade the package

        <spring-context.version>5.3.7</spring-context.version>
        
	<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-context.version}</version>
    </dependency>

Consider defining a bean named ‘entityManagerFactory‘ in your configuration.

After tossing all afternoon, I began to think that it was the problem of using JPA warehouse. I replaced the simplest JPA repository, but it still couldn’t work. I checked online and tried the following methods:

Delete the version number;

Delete all the files in the folder (. M2) and then import the package again by Maven;

At a loss, I found that I had commented on the main startup class

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

It’s equivalent to not allowing automatic injection of data source. Of course, entitymanagerfactory can’t be found…

Hope to be able to help small partners who encounter the same difficulties!

Springboot running shows application run failed [How to Solve]

Error:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-06-28 14:27:13.827 ERROR 7512 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

Background

It’s time to review. The teacher asked me to write a springboot project, but I couldn’t run it. Running application shows that application cannot be run
some errors were encountered in the process. I searched Baidu, and the result is as follows:
in the annotation of application, there is @ springbootapplication , which should be replaced by @ springbootapplication (exclude = datasourceautoconfiguration. Class) , but the result still doesn’t work.

Exclude to exclude such autoconfig, that is, to prohibit springboot from automatically injecting data source configuration. In this case, the automatic injection of mybits is excluded. As a result, there is a problem in the mapper layer.

Let the teacher have a look today. There is something wrong with the YML file.

Forget to write spring keywords, which I don’t understand.

server:
  port: 5050 # tomcat port
  servlet:
    context-path: /UserModel

spring:# I forgot to write it here, so that datesource belongs to the server
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/1202?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    username: root
    password: root

An error occurred while accessing the controller

The error reported is the same as this:

would dispatch back to the current handler URL [/UserModel/queryUserById] 

The difference between @Controller and @RestController is actually confusing
@Controller, @RestController?
Forgot the difference between get and post

Written by.
http://localhost:5050/UserModel/deleteUserByIds?ids=3,4

[Solved] Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerExcepti

 

1、 Background description

Project architecture: spring boot (v2.0.0. Release) + mybatis plus (v3.1.1)

Today, I developed a new function on an old project (running normally). Before adding new functions, the project started and ran normally. As a result, after the development, the project couldn’t start and the background didn’t report any error information. The key is that I didn’t even have a log. For a moment, I couldn’t start it.

2、 Cause analysis

According to the situation analysis, the project can’t be started. Thinking that there must be a problem in starting, a try… Catch… Block is added to the line of starting the project in the starting class (that is, the following code plus).

SpringApplication.run(DailyApplication.class, args);

See if there is an error log.

@Slf4j
@EnableScheduling
@EnableFeignClients(basePackages = "com.iot")
@SpringBootApplication(scanBasePackages={"com.iot"})
@MapperScan({"com.iot.daily.*.dao"})
public class DailyApplication implements ApplicationRunner {

    public static void main(String[] args) {
        try {
            SpringApplication.run(DailyApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error: ============== ", e);
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("The daily report system was successfully launched!......");
    }
}

Start the project, and then, as expected, the console displays the error log with the following error message:

Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat

The specific error information will be supplemented later, but now it can’t be reproduced.

3、 Solutions

Here is my project solution, very simple, Maven clean once, and then restart.

end!

Application failed to start

Error recurrence

Cause: the database related auto configuration library was imported, but the database was not configured in the configuration file.
solution: just exclude the database and add the following on the startup class annotation:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Springboot startup error could not resolve placeholder XXX

An error was reported when launching the springboot project today

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'spring.datasource.druid.initialSize' in value "${spring.datasource.druid.initialSize}"

First, confirm whether the field exists in the configuration file and whether the field name is written correctly. If it is confirmed that there is no error, check whether the configuration file is referenced. Generally, we will configure different configuration files in different environments, so we need to specify which configuration file to use in application.yml

spring:
  profiles: 
    active: druid

During the startup process, which file is used will be output. Note that if there is no output, it means that it has no effect

if you check the above, you can try build – & gt; Rebuild project try to rebuild and I succeed.

[Solved] “Field pet in XXX.HelloController required a bean of type ‘XXX.Pet‘ that could not be found.“

abnormal

2021-06-22 14:10:56.860 ERROR 17884 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field pet in com.demo.springboot.controller.HelloController required a bean of type 'com.demo.springboot.bean.Pet' that could not be found.

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

The following candidates were found but could not be injected:
	- Bean method 'pet' in 'MyConfig' not loaded because @ConditionalOnBean (names: user01; SearchStrategy: all) did not find any beans named user01


Action:

Consider revisiting the entries above or defining a bean of type 'com.demo.springboot.bean.Pet' in your configuration.

reason

Let’s analyze the printed error log

Let’s look at the hellocontroller class, in which the bean component of pet type is injected, but an error is reported that the injection is not successful

Then, we click the arrow icon on the left to go to the method of injecting this component. We find that it is the pet () method of the myconfig class, where the @ bean annotation is used to inject the pet component.

However, we use @ conditionalonbean (name = user01) annotation above the @ bean annotation, which means that a component named “user01” must exist in the container before the pet component can be injected, otherwise it will not be injected.

solve

Cancel the @ conditionalonbean (name = user01) annotation, or inject a component named “user01”.

But what is the reason for this mistake?Note that the bean component to be used by the @ conditionalonbean annotation condition should be declared above the annotation, not below.

Caused by: java.lang.ClassNotFoundException: com.alibaba.nacos.api.naming.NamingMaintainService

About the exception caused by: java.lang.classnotfoundexception: com.alibaba.nacos.api.naming.namingmaintainservice

I recently reported this exception when I started the project with springboot. I searched the Internet for various reasons and finally found that:

<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-client</artifactId>
    <version>1.2.0</version>
</dependency>

Plus the above dependence to solve this problem, troubled for more than an hour, wait to calm down just want to understand, record here!!!

Spring Boot Druid Error: discard long time none received connection

Spring boot integration Druid exception

In the spring boot integrated Druid project, the following error messages are frequently found in the error log:

discard long time none received connection. , jdbcUrl : jdbc:mysql://******?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8, version : 1.2.3, lastPacketReceivedIdleMillis : 172675

After troubleshooting, it was found that the exception was caused by Druid version, which did not appear in version 1.2.2 or earlier. In the above versions, there is this problem, the following is to analyze the causes of the exception and solutions.

Anomaly analysis

First of all, the above exception does not affect the normal operation of the program, but as a programmer to see the program constantly abnormal or intolerable. So we still need to get to the bottom of it.

Trace the stack information and find that the corresponding exception is thrown from the com.alibaba.druid.pool.druidabstractdatasource # testconnectioninternal method. The corresponding code is as follows:

if (valid && isMySql) { // unexcepted branch
    long lastPacketReceivedTimeMs = MySqlUtils.getLastPacketReceivedTimeMs(conn);
    if (lastPacketReceivedTimeMs > 0) {
        long mysqlIdleMillis = currentTimeMillis - lastPacketReceivedTimeMs;
        if (lastPacketReceivedTimeMs > 0 //
                && mysqlIdleMillis >= timeBetweenEvictionRunsMillis) {
            discardConnection(holder);
            String errorMsg = "discard long time none received connection. "
                    + ", jdbcUrl : " + jdbcUrl
                    + ", jdbcUrl : " + jdbcUrl
                    + ", lastPacketReceivedIdleMillis : " + mysqlIdleMillis;
            LOG.error(errorMsg);
            return false;
        }
    }
}

In the above code, mysqlutils.getlastpacketreceivedtimems (conn) is to get the last used time, mysqlidle millis is to calculate the idle time, and timebetweenevecitionrunsmillis is a constant of 60 seconds. If the connection is idle for more than 60 seconds, the discard connection (holder) discards the old connection and prints a log. Warn (errormsg) along with it.

Principle tracing

In the above code, we can see that there is a prerequisite for entering the business logic, that is, the variables valid and ismysql are true at the same time. It is necessary for ismysql to be true. What we use is the MySQL database. Can I make valid false?In this way, it will not enter the business processing?

Let’s take a look at the source of the valid method

boolean valid = validConnectionChecker.isValidConnection(conn, validationQuery, validationQueryTimeout);

We find the MySQL implementation subclass of validconnectionchecker, MySQL validconnectionchecker. The implementation of isvalidconnection in this class is as follows:

public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
    if (conn.isClosed()) {
        return false;
    }

    if (usePingMethod) {
        if (conn instanceof DruidPooledConnection) {
            conn = ((DruidPooledConnection) conn).getConnection();
        }

        if (conn instanceof ConnectionProxy) {
            conn = ((ConnectionProxy) conn).getRawObject();
        }

        if (clazz.isAssignableFrom(conn.getClass())) {
            if (validationQueryTimeout <= 0) {
                validationQueryTimeout = DEFAULT_VALIDATION_QUERY_TIMEOUT;
            }

            try {
                ping.invoke(conn, true, validationQueryTimeout * 1000);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof SQLException) {
                    throw (SQLException) cause;
                }
                throw e;
            }
            return true;
        }
    }

    String query = validateQuery;
    if (validateQuery == null || validateQuery.isEmpty()) {
        query = DEFAULT_VALIDATION_QUERY;
    }

    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = conn.createStatement();
        if (validationQueryTimeout > 0) {
            stmt.setQueryTimeout(validationQueryTimeout);
        }
        rs = stmt.executeQuery(query);
        return true;
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
    }

}

We can see that there are three return places in the above methods: the first connection is closed; The second uses Ping to check; Third, use select 1 to check. When Ping is used, it will return true no matter whether the exception is thrown or not. Here we can disable this mode.

The business logic of Ping mainly depends on the variable usepingmethod. Tracing code will find the settings here:

public void configFromProperties(Properties properties) {
    String property = properties.getProperty("druid.mysql.usePingMethod");
    if ("true".equals(property)) {
        setUsePingMethod(true);
    } else if ("false".equals(property)) {
        setUsePingMethod(false);
    }
}

In other words, when we set the system property Druid. Mysql. Usepingmethod to false, we can disable this function.

Disable ping method

After finding the root of the problem, the rest is how to disable it. There are usually three forms.

First, when starting the program, add: – Druid. Mysql. Usepingmethod = false in the running parameters.

Second, in the spring boot project, you can add the following static code to the startup class:

static {
    System.setProperty("druid.mysql.usePingMethod","false");
}

Third, class file configuration. In the druidconfig class of the project, add:

/*
* Resolving druid log errors: discard long time none received connection:xxx
* */
@PostConstruct
public void setProperties(){
    System.setProperty("druid.mysql.usePingMethod","false");
}

So far, the function has been successfully turned off, and the exception information will never appear again.

Why clear connections that are idle for more than 60 seconds

It is speculated that the idle waiting time of the database set by Alibaba is 60 seconds. When the MySQL database reaches the idle waiting time, the idle connection will be closed to improve the processing capacity of the database server.

The default idle waiting time of MySQL is 8 hours, which is “wait”_ “Timeout”. If the database actively closes the idle connection, but the connection pool does not know that it is still using the connection, an exception will be generated.

JAVA: Controller exception handling

With the @controlleradvice annotation, @exceptionhandler can specify the subdivision type of the exception on the specified controller

@ControllerAdvice
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * Parameter type conversion error
     *
     * @param exception error
     * @return error message
     */
   @ExceptionHandler(HttpMessageConversionException.class)
   public String parameterTypeException(HttpMessageConversionException exception){       
        logger.error(exception.getCause().getLocalizedMessage());
        return ResultErr("Type conversion error");
   }

	/**
	 * Uniform exception handling
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public String handlerException(Exception e) {
	    logger.error("Data check failure : errorMessage{"+e.getMessage()+"}");
		return ResultErr(e.getCode(), e.getMessage());
	}
	
}