Tag Archives: spring

NACOS error com.alibaba.nacos.api.exception.NacosException: failed to req API:/api//nacos/v1/ns/instance

service registry to nacos error: com. Alibaba. Nacos. API. Exception. NacosException: failed to the req API:/API// nacos/v1/ns/instance after all the servers ([192.168.175.100:1111]) tried: java.net.ConnectException: Refuse a Connection (Connection union)

after looking for a long time without finding the reason, it turns out that as long as you modify spring.application.name, it can be restored to normal:

so that it can start normally, which is very strange.

sometimes stops the service, restarts it and can’t be registered, and then changes the service name again.

Springboot project startup exception – required a single bean, but 2 were found

springboot project startup exception – required a single bean, but 2 were found

    • description
    • detailed error message
    • error analysis
    • why
    • solution

    problem description

    springboot+mybatis, write interface and implementation classes, and use @autowired injection controller, start exception: required a single bean, but 2 were found

    controller interface:

    @RestController
    @RequestMapping("/api/sys/statistic")
    public class StatisticController {
    
        @Autowired
        private ISysAccessLogService iSysAccessLogService;
        
    }
    

    interface and implementation class

    detail error

    APPLICATION FAILED TO START
    Description:

    Field iSysAccessLogService in com.msb.sys.controller.StatisticController required a single bean, but 2 were found:
    – sysAccessLogServiceImpl: defined in file [/Users/ronghuilin/java/msbjava/target/classes/com/msb/sys/service/impl/SysAccessLogServiceImpl.class]
    – ISysAccessLogService: defined in file [/Users/ronghuilin/java/msbjava/target/classes/com/msb/sys/service/ISysAccessLogService.class]

    Action:

    Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

    Disconnected from the target VM, address: ‘127.0.0.1:61739’, transport: ‘socket’

    error analysis

    if you’re prompted, there’s no way to automatically inject iSysAccessLogService at StatisticController.

    @autowired is injected by type by default, and as prompted, my project has two beans of this type, so it cannot be injected automatically.

    The

    error message also suggests a solution:
    1. Use one of the beans with the @primary annotation as the default,
    2. Add @qualifier to the injected property to specify beanName to specify which bean

    to use

    but I’ve only written one implementation class for the interface, and as expected there’s only one bean, which should be fine.

    Reason

    after a roundabout search, I found that I had annotated springboot’s boot class with @mapperscan (” “com”).

    @mapperscan this is the annotation is the Mapper scan annotation for mybatis, and the scope of the scan I specified is the com package.
    mybatis scans the interface under com, generates the implementation class of the interface, and infuses it into spring.
    then spring scans the interface implementation class I wrote, injects spring, and you have two beans.

    solution

    in the springboot project it is recommended to add @mapper directly to the Mapper interface and not to use @mapperscan.

    if you want to use @mapperscan annotations, be careful to configure the scope of the scan to avoid the above problems caused by repeat scan injection of spring beans.

Solve the problem that the value in the disabled tag cannot be passed to the server

disable tag values do not pass values to the server

<input type="text" name="did" value="${dept.did}" disabled="disabled"/><br/>

solution

  1. replace the field disabled in the form with readonly (if necessary, add a gray background color to the form)

    <input type="text" name="did" value="${dept.did}" readonly/><br/>
    

  2. you can write a hidden attributes, one for the value of a is used to display

    for example: add a hidden TAB and the name and value are set to the same value as the disable tag to successfully pass the value

    <input type="hidden" name="did" value="${dept.did}" >
    <input type="text" value="${dept.did}" disabled="disabled"/><br/>
    

    disabled

    similarity

    • can make text boxes cannot be entered.
    • can be modified by js script.
    • want to cancel, can only delete the corresponding attribute, set flase invalid

    different points

    disabled

    • input cannot receive focus
    • using the TAB key will skip the element
    • disabled will not respond to any event (e.g. the click event is invalid). The value of the disabled element
    • is not committed. The
    • disabled property can be used on all form elements.

    readonly

    • input can receive focus
    • use the TAB key does not skip elements
    • readonly will respond to events.
    • readonly element values are submitted. The
    • readonly property is only valid for type= “text”, textarea, and type= “password”.

    disabled will not be submitted to the server can’t be serialized but can be js can’t be modified on the interface all controls have disabled property

    readonly will be submitted to the server can be serialized can be js value assignment interface can’t modify all controls not necessarily have readonly property such as select drop down box

Springboot integrated with mybatis

springBoot integration mybatis

#springBoot integration with the first mybatis project
1. Create a new normal maven project
2. Use idea’s easycode to automatically generate the controller, entity, service and dao layer code
3. Simple pom configuration, independent of error

  java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class tk.mybatis.spring.annotation.MapperScan.factoryBean()

依赖如下:
   <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>  
       <version>2.1.0</version>
   </dependency>
    <dependency>
       <groupId>com.oracle</groupId>
       <artifactId>ojdbc6</artifactId>
       <version>11.2.0.4</version>
   </dependency>

4.  配置简单的yml,不配置会报找不到 

mybatis:
mapper-locations:类路径:mapper/* . xml

Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constr

error when learning the fourth edition of spring in action AOP book:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'knight' defined in class path resource [resources/minstrel.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#1784306' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1784306': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'knight' defined in class path resource [resources/minstrel.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#1784306' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1784306': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:479)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
	at main.java.sia.knights.KnightMain.main(KnightMain.java:9)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#1784306' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1784306': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:313)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
	at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:648)
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1201)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
	at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
	at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:102)
	at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
	at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:248)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1045)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1019)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:473)
	... 10 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1784306': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
	at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1201)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299)
	... 28 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1163)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1107)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:331)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
	... 36 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
	... 42 more
Caused by: java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
	at java.lang.Class.getDeclaredConstructors0(Native Method)
	at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
	at java.lang.Class.getConstructor0(Class.java:3075)
	at java.lang.Class.getDeclaredConstructor(Class.java:2178)
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
	... 43 more
Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException
	at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 48 more

under the online to find the reasons, found that it is no use to import the jar package (it’s strange that I have is in accordance with the project with the idea to create a spring, why am I still missing bag), and then find is the lack of aspectjweaver – 1.9.4. Jar the jar package, in the following website to download the jar package:

https://mvnrepository.com/ download, to import the jar package, and compile: find and mistake

七月 19, 2019 11:07:17 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6a30c7: startup date [Fri Jul 19 23:07:17 CST 2019]; root of context hierarchy
七月 19, 2019 11:07:17 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [resources/minstrel.xml]
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'knight' is expected to be of type 'main.java.sia.knights.BraveKnight' but was actually of type 'com.sun.proxy.$Proxy2'
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:384)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1086)
	at main.java.sia.knights.KnightMain.main(KnightMain.java:12)

continue to look for reasons: spring aop proxy mix, in the XML configuration added configuration :
< Aop: aspectj – autoproxy proxy – target – class = “true”/& gt;
error resolution.
agent hybrid solution

[springboot] problem failed to determine a suitable driver class

recently took over a new project under development, the result of importing IDEA couldn’t run, error:

Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name ‘servletEndpointRegistrar’ defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method ‘servletEndpointRegistrar’ threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘healthEndpoint’ defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method ‘healthEndpoint’ parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘healthIndicatorRegistry’ defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthIndicatorRegistry]: Factory method ‘healthIndicatorRegistry’ threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthIndicatorAutoConfiguration’: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/DruidDataSourceAutoConfigure.class]: Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

took a long time to troubleshoot the error, and finally it was found that the resource folder recognition failed. It turns out that when SpringBoot automatically loads configuration files via AutoConfigure, it is necessary to ensure that the resource folder under SRC folder is a resource folder. As shown in , the resource folder will have several small horizontal bar marks in the lower right corner, while the normal folder is not. Right-click on Make Dictionary as and change the normal folder to the resource folder, and the project will start normally.

Idea couldn’t be found org.springframework.context .support

use maven spring project management idea, operation times can’t find the org. Springframework. Context. The support.
reason: jar package has not been imported, or idea cannot find this jar package, need to check the configuration of maven
solution:
1. Reimport maven pom file
2. Check that the version of the jar package is compatible with the currently used JDK version
3. 4. Delete the configuration of localrepository in the conf folder in the maven installation directory. Manually specify the address of the localrepository in idea

Simple use of namedparameterjdbctemplate of spring

Spring JDBC package provides a JdbcTemplate and its two brothers SimpleJdbcTemplate and NamedParameterJdbcTemplate.

NamedParameterJdbcTemplate class is based on the JdbcTemplate class, and it is encapsulated to support named parameter feature.

NamedParameterJdbcTemplate mainly provides the following three methods: the execute method, method of query and queryForXXX, update and batchUpdate method.

Example in the

project:

String username = “root”;
String password = “root”;
String driver = “com.mysql.jdbc.driver”;
String url = “JDBC: mysql:// 127.0.0.1:3306/upwis_flow?CharacterEncoding = utf-8 “;

	Class.forName(driver);
	Connection conn= DriverManager.getConnection(url, username, password);

	DataSource dataSource=new SingleConnectionDataSource(conn,false);
	NamedParameterJdbcTemplate jdbc=new NamedParameterJdbcTemplate(dataSource);
	jdbc.getJdbcTemplate();
	List list = jdbc.queryForList("select * from fw_dir",new HashMap<>());
	System.out.println(list);

Spring boot thymeleaf crud implements simple functions of adding, deleting, modifying and querying

introduction

this article introduces a simple CRUD application using spring boot and Thymeleaf.

create Maven project

here to create a maven-based project using intellij community edition

overall architecture

Add Maven dependencies

database selected H2 lightweight database, convenient configuration, default configuration data written into memory, restart service lost, configuration data can be written to the file.

  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.6.RELEASE</version>
  </parent>
  <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-devtools</artifactId>
          <scope>runtime</scope>
      </dependency>
      <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <scope>runtime</scope>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
      </dependency>
  </dependencies>

Domain layer
The

layer defines the entity class for data interaction. Here we define the Student class.

package com.springbootcrud.entity;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @NotBlank(message = "Name is mandatory")
    @Column(name = "name")
    private String name;

    @NotBlank(message = "Email is mandatory")
    @Column(name = "email")
    private String email;

    @Column(name = "phoneNo")
    private long phoneNo;

    public Student() {
    }

    public Student(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public long getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(long phoneNo) {
        this.phoneNo = phoneNo;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", phoneNo=" + phoneNo +
                '}';
    }
}

repository layer

is the persistence layer that interacts with the database. Here, the implementation of adding, deleting, modifying and checking entity classes in the database is specifically implemented. Here, we inherit the corresponding classes of the spring data framework instead of implementing the Dao layer implementation method by ourselves.

package com.springbootcrud.repository;

import com.springbootcrud.entity.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentRepository extends CrudRepository<Student, Long> {
    List<Student> findByName(String Name);
}

controller layer

this layer is responsible for processing the user’s input and returning the correct response back to the user.

package com.springbootcrud.controller;

import com.springbootcrud.entity.Student;
import com.springbootcrud.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/students/")
public class StudentController {

    private final StudentRepository studentRepository;

    @Autowired
    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @GetMapping("signup")
    public String showSignUpForm(Student student) {
        return "add-student";
    }

    @GetMapping("list")
    public String showUpdateForm(Model model) {
        System.out.println(studentRepository.findAll());
        model.addAttribute("students", studentRepository.findAll());
        return "index";
    }

    @PostMapping("add")
    public String addStudent(@Valid Student student, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "add-student";
        }

        studentRepository.save(student);
        return "redirect:list";
    }

    @GetMapping("edit/{id}")
    public String showUpdateForm(@PathVariable("id") final long id, Model model) {
        Student student = studentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid student Id:" + id));
        model.addAttribute("student", student);
        return "update-student";
    }

    @PostMapping("update/{id}")
    public String updateStudent(@PathVariable("id") long id, @Valid Student student, BindingResult result, Model model) {
        if (result.hasErrors()) {
            student.setId(id);
            return "update-student";
        }

        studentRepository.save(student);
        model.addAttribute("students", studentRepository.findAll());
        return "index";
    }

    @GetMapping("delete/{id}")
    public String deleteStudent(@PathVariable("id") long id, Model model) {
        Student student = studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid student id:" + id));
        studentRepository.delete(student);
        model.addAttribute("students", studentRepository.findAll());
        return "index";
    }

}

View layer

user sees the specific web page view, combined with Thymeleaf populated data, shown to the user

add-student.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Add User</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <!-- <link rel="stylesheet" href="../css/shards.min.css"> -->
</head>

<body>
    <div class="container my-5">
        <h3>Add Student</h3>
        <div class="card">
            <div class="card-body">
                <div class="col-md-10">
                    <form action="#" th:action="@{/students/add}" th:object="${student}" method="post">
                        <div class="row">
                            <div class="form-group col-md-8">
                                <label for="name" class="col-form-label">Name</label> <input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Name"> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="text-danger"></span>
                            </div>
                            <div class="form-group col-md-8">
                                <label for="email" class="col-form-label">Email</label> <input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Email"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="text-danger"></span>
                            </div>
                            <div class="form-group col-md-8">
                                <label for="phoneNo" class="col-form-label">Phone No</label> <input type="text" th:field="*{phoneNo}" class="form-control" id="phoneNo" placeholder="PhoneNo"> <span th:if="${#fields.hasErrors('phoneNo')}" th:errors="*{phoneNo}" class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="submit" class="btn btn-primary" value="Add Student">
                            </div>
                            <div class="form-group col-md-8"></div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Users</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <!-- <link rel="stylesheet" href="../css/shards.min.css"> -->
</head>

<body>
    <div class="container my-2">
        <div class="card">
            <div class="card-body">
                <div th:switch="${students}" class="container my-5">
                    <p class="my-5">
                        <a href="/students/signup" class="btn btn-primary"><i class="fas fa-user-plus ml-2"> Add Student</i></a>
                    </p>
                    <div class="col-md-10">
                        <h2 th:case="null">No Students yet!</h2>
                        <div th:case="*">
                            <table class="table table-striped table-responsive-md">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Phone No</th>
                                        <th>Edit</th>
                                        <th>Delete</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="student : ${students}">
                                        <td th:text="${student.name}"></td>
                                        <td th:text="${student.email}"></td>
                                        <td th:text="${student.phoneNo}"></td>
                                        <td><a th:href="@{/students/edit/{id}(id=${student.id})}" class="btn btn-primary"><i class="fas fa-user-edit ml-2"></i></a></td>
                                        <td><a th:href="@{/students/delete/{id}(id=${student.id})}" class="btn btn-primary"><i class="fas fa-user-times ml-2"></i></a></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>

update-student.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Update User</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <!-- <link rel="stylesheet" href="../css/shards.min.css"> -->
</head>
<body>
    <div class="container my-5">
        <h3>Update Student</h3>
        <div class="card">
            <div class="card-body">
                <div class="col-md-8">
                    <form action="#" th:action="@{/students/update/{id}(id=${student.id})}" th:object="${student}" method="post">
                        <div class="row">
                            <div class="form-group col-md-6">
                                <label for="name" class="col-form-label">Name</label> <input type="text" th:field="*{name}" class="form-control" id="name" placeholder="Name"> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="text-danger"></span>
                            </div>
                            <div class="form-group col-md-8">
                                <label for="email" class="col-form-label">Email</label> <input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Email"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="text-danger"></span>
                            </div>
                            <div class="form-group col-md-8">
                                <label for="phoneNo" class="col-form-label">Phone No</label> <input type="text" th:field="*{phoneNo}" class="form-control" id="phoneNo" placeholder="PhoneNo"> <span th:if="${#fields.hasErrors('phoneNo')}" th:errors="*{phoneNo}" class="text-danger"></span>
                            </div>
                            <div class="form-group col-md-8">
                                <input type="submit" class="btn btn-primary" value="Update Student">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

run springboot application

program run entry.

package com.springbootcrud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

execution effect

Maven global configuration

IDE no other Settings method to configure Maven globally (one time Maven)

recently when I was writing code with idea, I found that every time I opened a new project, I had to reconfigure Maven, which was particularly troublesome. Baidu online many idea one-time configuration Maven method.
found File--> Other Settings
but I didn't find in my idea other Settings

so I began to baidu have no other idea Solution for Settings option. Some people say File--> Settings--> Other Settings other Settings in Settings

the end result is, of course, I didn't find it.
I finally found the Default Settings changed his name Settings For New Projects

then go to configuration with respect to OK

once again into the idea of Settings, found that the Maven has been configured.

generally speaking, I'm not careful enough. I wish I could help others.
is recorded for query purpose.

Springboot error: property ‘sqlsessionfactory’ or ‘sqlsessiontemplate’ are required error details

problem 1

is in the Mapper layer and it needs to be annotated with @mapper, but then someone put @respository online and it gets mixed up and it could be either one. It’s always going to be @mapper. Add the annotations, but if the Mapper layer in the configuration main class SpringBootMybatisApplication inside there is no need for @ MapperScan (” com. Example. Demo. Mapper “) scans annotations, add scan to the configuration class notes mean under this package all annotations into Mapper.

problem 2

SpringBoot project created with STS, where the configuration file defaults to application.properties, where the data source is typically configured. But want to play this file, you must add @ EnableAutoConfiguration to configure the main class (exclude = {DataSourceAutoConfiguration. Class}) automatic injection, otherwise the configuration in the configuration file is invalid. Failed to configure a DataSource: ‘URL’ attribute is not specified and no embedded DataSource could be configured. Error

but if this annotation is added at this time,

is dependent on the jar package in Mybatis

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</ version>
</dependency>

problem three

Automatic injection of SqlSessionFactory and SqlSessionTemplate is cancelled in

mybatis spring-1.3.2, so Property ‘SqlSessionFactory’ or ‘SqlSessionTemplate’ are required error will be reported.
you need to find a solution, so search the web for a solution, refer to this article, create a base class, and then let your dao inherit.

https://www.cnblogs.com/hawk0035/p/3337283.html?utm_source=tuicool

but my Mapper layer is using the annotated version of Mybatis, which is an interface and cannot inherit classes. So that’s not going to work.
since auto injection was eliminated in mybatis spring-1.3.2, I switched to a lower version of mybatis spring-1.1.1, but the fact remains the same, nothing has changed.

it is to find a way to don’t @ EnableAutoConfiguration (exclude = {DataSourceAutoConfiguration. Class}) automatic injection, so must the application. The properties to the application configuration file. The yml. The problem was finally solved.