Tag Archives: spring boot

Springboot uses druid to log in MySQL. An error occurred: access denied: errorcode 1045, state 28000

In case of an error, first of all, check whether the database can be accessed correctly through MySQL instructions:
it is found that the database can be accessed normally

later, when I observed my configuration, I found that my password was all digital. There would be a little problem with all digital passwords in the YML file, so I need to add ‘single quotation mark to correctly identify them. The correct configuration is as follows:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mall?useUnicode=true&characterEncoding=utf8&useOldAliasMetadataBehavior=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=UTC
    username: root
    password: '123456'
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

Error creating bean with name [How to Solve]

I ran into a bug today

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'skuController'


The solution:

1. Maybe the implementation class didn’t add @servcie annotation. After you add it, click start, and the error still exists. Heartbreak X1 2. It may be that @mapperscan (“com. XXX. Mapper”) is not added to the startup class. After you add it, click start, and the error still exists. Heartbreak x2 3. Maybe the Dao package in serviceimpl is not imported into @ Autowired. After you add it, click start, and the error still exists. How about heartbreak X3
is it endless fun to be immortal and die? In the end, you have listed three possibilities, but you still need a note:
@ enable autoconfiguration

@The main functions of enable autoconfiguration are as follows:

Enable automatic configuration of the spring application context and try to guess and configure the beans you may need. Automatic configuration classes are usually based on class paths and defined bean applications. For example, if you have
tomcat-embedded.jar in your classpath, you may want a Tomcat embedded servletcontainerfactory (unless you define your own embedded servletcontainerfactory
bean). When using springbootapplication, automatic configuration of the context is automatically enabled and this annotation is added, so there is no extra effect
autoconfiguration tries to be as intelligent as possible and will be backed up when you define more of your own configurations. You can always manually exclude () any configuration you don’t want to apply (if you can’t access them). You can also exclude them through spring.
autoconfigure. Exclude attributes. After the user-defined bean is registered, auto configuration is always applied. Packages of classes annotated with @
enable autoconfiguration, usually through @
spring boot application, have special significance and are often used as “default”. For example, it will be used to scan the @ entity class. It is generally recommended to place @
enable autoconfiguration in the root package (if you do not use @ springbootapplication) so that you can search all subpackages and classes conditionalonclass and @ conditionalonsingbean).

The above explanations about @ enableautoconfiguration are copied from other places by bloggers. If it’s a bit difficult to understand, you just need to know that it’s Bean’s automatic assembly tool. Maybe you will ask, why do I do this?Can’t I use @ import directly in my project?Of course, since it is automatic configuration, of course, you want the project to start and load.

 

[Solved] com.alibaba.druid.pool.DruidDataSource – create connecti

A service deployed in the server docker reported the following error when connecting to the database:

I have searched a lot of information on the Internet, but I can’t solve it by trying various ways,
ERROR com.alibaba.druid.pool.DruidDataSource - create connection SQLException, url: jdbc:mysql://10.10.20.16:3306/acs?&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Kolkata, errorCode 0, state 08S01
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

The specific error information is as follows:

ERROR com.alibaba.druid.pool.DruidDataSource – create connection SQLException, url: jdbc:mysql ://10.10.20.16:3306/acs?& amp; useUnicode=true& characterEncoding=UTF-8& zeroDateTimeBehavior=convertToNull& allowMultiQueries=true& serverTimezone=Asia/Kolkata, errorCode 0, state 08S01
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Cause of error:

It may be due to the different versions of JDK. This error message is probably caused by the SSL protocol of MySQL

solution: I tried to remove SSLv3 from java.security in jdk-8 on my local machine and restart the service, but I still couldn’t solve it
finally, add this to the MySQL connection string in the service configuration; Usessl = false, that is, disable SSL, problem solved

[Solved] Error getting bean using springboot: no qualifying bean of type ‘xxx’ available

Recently, I encountered a bug in my work.
the project uses springboot, and uses springcontexthloder, getBean (); No qualifying bean of type ‘xxx’ available

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tension.web.disabledevaluate.service.DisabledEvaluateService' available

Generally, this error indicates that there is no bean available. Check the code carefully to ensure that this class exists and is injected into spring correctly

Controller:

 public Map loadForm(String round,String instanceId) {
 		//error
        DisabledEvaluateService disabledEvaluateService = SpringContextHolder.getBean(DisabledEvaluateService.class);
 }

Service:

@Service
@Transactional(readOnly = true)
public class DisabledEvaluateService extends CrudService<DisabledEvaluateDao, DisabledEvaluate> {
    public DisabledEvaluate getByBjId(Map map){
        return dao.getByBjIdOrInstanceId(map);
    }

After several hours of exploration, we finally found the information on the Internet because we used the devtools hot deployment plug-in. As a result, when the program starts, we use the classloader rewritten by the devtools hot deployment plug-in instead of the Java default classloader. As a result, some classes may not be loaded correctly, resulting in the inability to obtain beans.

Solution:
this error can be solved without using hot deployment plug-in

java.nio.charset.MalformedInputException: Input length = 1

Project scenario:

Using springboot to build a personal blog system
reference video: reference video link

Problem Description:

Error reported:

20:40:41.091 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1
	at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218)
	at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176)
	at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171)
	at org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126)
	at org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1177)
	at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:287)
	at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227)
	at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195)
	at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
	at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148)
	at org.yaml.snakeyaml.composer.Composer.checkNode(Composer.java:82)
	at org.yaml.snakeyaml.constructor.BaseConstructor.checkData(BaseConstructor.java:123)
	at org.yaml.snakeyaml.Yaml$1.hasNext(Yaml.java:507)

Cause analysis:

I remember converting the suffixes of properties files to YML files directly according to the video, and then the Chinese comments on the page became garbled, so I naturally converted them to GBK format, and then the above error was reported

The first possibility is that there is a problem with the encoding format of your application.yml file, which is changed to UTF-8
the second possibility is that your application.yml file is generated by directly changing the suffix of other types of files to YML. At this time, you need to copy all the contents in application.yml, delete them, and then create a new application.yml file, Copy the copied content into it and then run the project, and no error will be reported.

Solution:

Find file coding in the setting of idea

Convert GBK to UTF-8, and then rewrite the Chinese annotation to run normally

Springboot Error: There was an unexpected error (type = internal server error, status = 500)

There was an unexpected error (type=Internal Server Error, status=500).
This error was found in running springboot.

There was an unexpected error (type=Internal Server Error, status=500).
Authentication failed for token submission [org.apache.shiro.authc. UsernamePasswordToken – null, rememberMe=false]. Possible unexpected error?(Typical or expected login exceptions should extend from AuthenticationException).
I had to rewrite it and found out that it was caused by Maven and the Thymeleaf dependency was added incorrectly.
Maybe I wrote it and @{} didn’t work correctly, so I took one from the internet and got the wrong one.
The original dependency was this

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

I ended up with this

<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

Servlet.service() for servlet [dispatcherServlet] in context && Whitelabel Error Page

ERROR 8040 – O.A.C.C.C. [nio – 8080 – exec – 1]. [[. [/] [dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

to find for a long time, found and @autowired didn’t add question
service plus, didn’t add mapper

Can’t Dubbo’s @ service be injected into the spring container?

Solution: rebuild the module and test again
when testing the Dubbo provider, adding @ service under the Dubbo path to the business implementation code will report that a test class is not injected
org.springframework.beans.factory.unsatisfied dependencyexception: error creating bean with name ‘com.tanhua.dubbo.server.api.testrecommenduserapi XXXXXX,
No qualifying bean of type ‘com. Tanhua. Dubbo. Server. API. Recommenduserapi’ available: (I think the interface recommenduserapi was not injected), so I replaced it with spring’s @ service line; But shouldn’t Dubbo’s @ service have spring’s @ service function?Baidu for a long time did not belong to their correct answer; After carefully checking the scan package, the annotation @ runwith (springrunner. Class) @ springboottest
on the test class has been added, and the @ service under Dubbo still reports an error
at last, the module was simply rebuilt by copying and pasting, and the final test was successful!! But what’s wrong?I don’t know. Maybe it’s related to building a module! Hope it works…

No qualifying bean of type ‘javax.sql.DataSource‘ available: expected at least 1

The startup class has been configured

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

The error information is as follows:

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Reason: the default datasource is used.
solution: start the accumulation configuration

  @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

Aspecj cannot intercept method annotations on an interface

Aspecj cannot intercept method annotations on an interface

Aspecj can’t intercept the method annotation on the interface, it can only act on the method of the implementation class. At this time, it needs to use methodinterceptor to implement.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface AopTest {
}

Interface

public interface TestAOPI {
    @AopTest
    public String test();

}

Implementation class 1

@Service
public class TestAOPService implements TestAOPI{
    @Override
    public String test() {
        return "service";
    }
}

Implementation class 2

@Service
public class TestAOPService2 implements TestAOPI{
	@AopTest
    @Override
    public String test() {
        return "service";
    }
}

Aspecj (partially valid)

If and only if the @ aoptest annotation is added to the method of the implementation class, it will take effect (implementation class 2), but implementation class 1 will not

@Aspect
@Configuration
public class AopTestAspect {
  /**
     * Identifies the method annotated with OperationLog
     */
    @Pointcut("@annotation(com.example.demo1.config.AopTest)")
    public void methodHasAopTestAnnotation() {
    }
    
    @Around("methodHasAopTestAnnotation()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("aop!!!");
        return joinPoint.proceed();
    }
}

Solution

It needs to be changed to the following way by manual

@Configuration
public class AopTestConfiguration {
	@Bean
    public Advisor methodPointcutAdvisor() {
        AopTestMethodPointcutAdvisor advisor = new AopTestMethodPointcutAdvisor();
        advisor.setAdvice(new AopTestInterceptor());
        return advisor;
    }

    class AopTestInterceptor implements MethodInterceptor {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            String name = invocation.getMethod().getName();
            System.out.println("==============" + name + " before ================");
            Object result = invocation.proceed();
            System.out.println("==============" + name + " after ================");
            return result;
        }
    }
    public class AopTestMethodPointcutAdvisor extends StaticMethodMatcherPointcutAdvisor {
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
        	// Implementing a class method with a target annotation on it
            if(method.isAnnotationPresent(AopTest.class)){
                return true;
            }
            // The method has a corresponding interface method and the interface method is annotated
            Class<?>[] interfaces = method.getDeclaringClass().getInterfaces();
            for (int i = 0; i < interfaces.length; i++) {
                Method[] methods = interfaces[i].getMethods();
                for (int j = 0; j < methods.length; j++) {
                    if(methods[j].getName().equals(method.getName())){
                        return methods[j].isAnnotationPresent(AopTest.class);
                    }
                }
            }
            return false;
        }
    }
}

Spring boot real time HTML page

Add the following configuration in application. Properties

spring.thymeleaf.cache=false # close cache

Introduce debugging tools into POM. XML and set it to open

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

alt + ctrl + S open settings:
Build,Execution,Deployment —— Complier:
Check Build project automatically
ctrl + shift + alt + /:
Check Registry
Check compiler.automake.allow.when.app.running

[neo4j] error report when visiting neo4j in spring boot project

Spring boot project uses spring-data-neo4j to connect with neo4j. It can start and access the database normally when running locally all the time. If you write dockerfile well and run on the server with docker compose, you will report an error, such as:

Caused by: java.lang.NullPointerException: null
    at org.neo4j.ogm.MetaData.entityType(MetaData.java:280) 

The reasons are as follows:
https://github.com/spring-projects/spring-boot/issues/6709

stay pom.xml To solve the problem, add dependency to

 <!--Not adding this package to run in docker will report an error-->
 <!--https://github.com/spring-guides/gs-accessing-data-neo4j/issues/19-->
        <dependency>
            <groupId>io.github.lukehutch</groupId>
            <artifactId>fast-classpath-scanner</artifactId>
            <version>3.1.13</version>
        </dependency>