Springboot Getting Started Usage Example Analysis
Getting Started with Springboot
Project creation can be created in IDEA.
Notes:
1. All files need to be placed in:
The same level or lower level directory of the Application file In
2, application.properties is the main core configuration file of the spring-boot project, and there can only be one core configuration file.
3. When using core configuration files in multiple environments, the file name must start with application-!
application-xxx.properties
(1) Development environment
# 开发环境配置文件 server.port=9000 server.servlet.context-path=/
(2) Test
# 测试环境配置文件
( 3) Production environment
# 生产环境配置文件 server.port=7000
Activate our customized configuration file in the main core configuration file:
#激活我们编写的application-xxx.properties配置文件 spring.profiles.active=dev
4, @Value annotation
spring -How to obtain the custom configuration attributes of the boot core configuration file
The following method can only obtain one attribute at a time!
For example: a configuration website=http://www.baidu.com is customized in the application.properties file
Get this customized configuration in the project:
Use annotation@ Value("${website}")
You can also write a default value. If there is no configuration item, the default value will be used@Value("${website: default value}")
package com.lxc.sprint_boot_01.web; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.management.ValueExp; import javax.print.DocFlavor; // 声明控制层 @Controller public class IndexController { @Value("${website:values}") private String name; // 此时website值会赋给name属性 @RequestMapping(value = "/self") @ResponseBody public String self() { return name; } }
5, @Component and @ConfigurationProperties(prefix="xxx") annotations
spring-boot core configuration file maps our custom configuration properties to an object (the obtained An object), the prerequisite for using this method: the attributes in the configuration file must be prefixed!
application.properties file
# 属性前边必须要有前缀,我这里前缀是user user.name=lxc user.password=123456
config -> user.java file
package com.lxc.sprint_boot_01.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component // 将此类交给spring容器管理 @ConfigurationProperties(prefix = "user") // 配置属性注解,参数前缀必须有值,值为我们定义的前缀 // 配置完上边的两个注解,下边把配置文件中的属性映射到下边类中去 public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Calling properties
package com.lxc.sprint_boot_01.web; import com.lxc.sprint_boot_01.config.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.management.ValueExp; import javax.print.DocFlavor; import java.util.HashMap; import java.util.Map; // 声明控制层 @Controller public class IndexController { @Autowired // @Autowired 把User类注入进来 private User user; @RequestMapping(value = "/many") @ResponseBody public String many() { return "user为:"+user.getUsername() + ",密码为:"+user.getPassword(); } }
6. If you add the @ConfigurationProperties annotation, the red warning above will appear. To solve this problem, you need to add a dependency package:
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-configuration-processor</artifactid> </dependency>
7 . If there are Chinese characters in application.properties, garbled characters will appear. Solve the problem of Chinese garbled characters in IDEA:
8. In the configuration file The key-value pair of the attribute cannot have spaces, otherwise there will be problems with parsing!
9. Spring-boo integrated JSP
First create the webapp folder under the main folder, and then click file -> ; project structure -> Modules As shown below:
Then click on the file on the right in the pop-up dialog box and find us Just confirm the webapp folder you just created. The details are as follows:
At this time, the webapp will become as follows.
Configuring the pom.xml file
(1) First introduce the spring-boot embedded tomcat's dependency on jsp parsing, and jsp cannot be parsed without adding it
<!--引入spring-boot内嵌的tomcat对jsp的解析依赖,不添加解析不了jsp--> <dependency> <groupid>org.apache.tomcat.embed</groupid> <artifactid>tomcat-embed-jasper</artifactid> </dependency>
(2) Spring-boot uses the front-end engine thymeleaf by default. Now we want to use springboot to inherit jsp. We need to manually specify the path of the last compiled jsp, and the path for springboot to inherit jsp is the location specified by springboot: META-INF/resources
<build> <!--spring-boot默认使用的是前端引擎thymeleaf,现在我们要使用springboot继承jsp,需要手动指定jsp最后编译的路径,而且springboot继承jsp的路径是springboot规定好的位置:META-INF/resources--> <resources> <resource> <!--源文件--> <directory>src/main/webapp</directory> <!--指定编译路径:--> <targetpath>META-INF/resources</targetpath> <!--指定源文件夹中的哪些资源需要被编译--> <includes> <include>*.*</include> </includes> </resource> </resources> <plugins> <!-- ··· --> </plugins> </build>
The last step: Configure the view parser in application.properties
# 配置视图解析器 spring.mvc.view.prefix=/ # 前缀 spring.mvc.view.suffix=.jsp # 后缀
Create a .jsp page, test:
<title>Title</title> <h2 id="msg">${msg}</h2>
package com.lxc.boot_02; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class controller { // 写法一: @RequestMapping(value="/say") public ModelAndView say() { ModelAndView mv = new ModelAndView(); // 给视图传值 mv.addObject("msg", "hello"); // 设置 最终视图的名称 mv.setViewName("say"); return mv; } // 写法二:把视图和模型拆分开,返回一个视图(return的是视图的名字) @RequestMapping(value = "/index") public String index(Model model) { model.addAttribute("msg", "lxc;"); return "say"; } }
Writing method one:
Writing method two:
The above is the detailed content of Springboot Getting Started Usage Example Analysis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
