In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how Idea initializes background projects from scratch in Spring Boot". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how Idea initializes background projects from scratch in Spring Boot".
1 create Project 1.1 fill in the basic project information
Open Idea to create a project, as shown below:
1.2 Select Project Integration function
Complete the basic information configuration. In the Web,SQL,NoSQL,Ops option, select the corresponding module dependency, and finally select the following items as shown in the figure:
Spring Web is used to provide web-related functions
Spring Data JPA is used to provide database-related operations
MyBatis Framework is used to manipulate the database through MyBatis
Spring Data Redis is used to provide Redis-related functions
Spring Boot Actuator is used to provide health monitoring functions for applications.
When the setup is complete, click next, and Idea starts initializing the project file.
2 basic configuration of the project
Through the above steps, the project structure file has been generated, and the subsequent work can be continued after waiting for the development environment to build the dependent library automatically.
2.1 gradle File configuration
The current project uses gradle to manage project dependencies. By default, the official dependency library is used, and domestic access is slow, so it can be replaced with Aliyun warehouse. Add the access address of Ali Cloud Warehouse under the repositories node of the build.gradle file. After the configuration is completed, the following
Repositories {/ / use Aliyun Warehouse to improve the download speed of domestic dependent libraries maven {url "http://maven.aliyun.com/nexus/content/groups/public"} mavenCentral ()}
In addition, add other commonly used dependency libraries, and the final dependency package is as follows
Dependencies {implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation' org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-redis' implementation' org.springframework.boot:spring-boot-starter-web' implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.2' implementation' com.alibaba:fastjson:1.2.68' The log class com.mysql.cj.log.Slf4JLogger configured by implementation 'org.apache.commons:commons-lang3:3.10' / / database is runtime (' mysql:mysql-connector-java') testImplementation ('org.springframework.boot:spring-boot-starter-test') {exclude group:' org.junit.vintage' in this package Module: 'junit-vintage-engine'}} 2.2 Environment file configuration
By default, the official initializer generates an application.properties file under the resources resource folder. Here, adjust the configuration file structure. Create a config folder under the resources resource folder, move the application.properties file to the config folder, and create application-dev.properties file and application-prod.properties file under the config folder. Corresponding to the configuration of the development environment and online environment, you can add other environment configuration files as needed. The file format is application- environment name .properties.
The final application.properties file is as follows
# start dev environment by default, spring.profiles.active=dev# adjusts web backend service port to 9080, do not set default to 8080server.port=9080#mybatis configuration file address, mybatis.config-location=classpath:mybatis/mybatis-config.xml#mybatis mapper file address, mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
The content of application-dev.properties file is as follows
# mysql database connection spring.datasource.url=jdbc:mysql://localhost:3306/crane?autoReconnect=true&characterEncoding=UTF-8&useSSL=false&logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true&maxQuerySizeToLog=8192# database login Database spring.datasource.username=root# database password in docker mirror spring.datasource.password=crane# in native docker mirror redisspring.redis.host=127.0.0.1# current environment log configuration output to console logging.config=classpath:logback-dev.xml# enable all types of health monitoring management.endpoints.web.exposure.include=*
The contents of the application-prod.properties file are as follows (currently, only log files are distinguished from the dev environment, which can be adjusted according to actual needs)
# mysql database connection spring.datasource.url=jdbc:mysql://localhost:3306/crane?autoReconnect=true&characterEncoding=UTF-8&useSSL=false&logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true&maxQuerySizeToLog=8192# database login Database spring.datasource.username=root# database password in docker mirror spring.datasource.password=crane# in native docker mirror redisspring.redis.host=127.0.0.1# current environment log configuration output to console logging.config=classpath:logback-prod.xml# enable all types of health monitoring management.endpoints.web.exposure.include=*
Note: when configuring the database link spring.datasource.url, it should be noted that the mysql:mysql-connector-java referenced by the current project is version 8.0.19, the path of the MySQL log printing class Slf4JLogger class is com.mysql.cj.log.Slf4JLogger, and the older version is under the com.mysql.jdbc.log.Slf4JLogger path.
2.2.1 Logback profile
The logback-dev.xml contents of the logback configuration file corresponding to the dev environment are as follows, and the log is output to the console.
% yellow ([% date {yyyy-MM-dd HH:mm:ss.SSS}])% highlight ([%-5level])% cyan ([% thread]) -% msg [% logger {1}]\ (% file:%line\)% n
The logback-prod.xml contents of the logback configuration file corresponding to the prod environment are as follows, and the log is output to the file.
Log/hbackend.log log/hbackend-%d {yyyy-MM-dd} .log [% date {yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [% thread] -% msg [% logger {1}]\ (% file:%line\)% n 2.2.2 MyBatis profile
The contents of the mybatis-config.xml file are as follows, there is currently no configuration, all use the default configuration.
3 simple cases
The current case implements basic Redis and MySQL operations, because the case simulates the back-end project building process and does not involve front-end UI presentation, so some interfaces use Postman to test usability. Create the controller class CommonController under the root folder of the project source file, which is used to provide data response to web requests, and set the controller access address, as follows
RestController@RequestMapping ("/ common") public class CommonController {private Logger logger = LoggerFactory.getLogger (this.getClass ());}
Create a HResponse class to construct the response result of the request, as follows
Public class HResponse {/ * status of request result * / private int status; private String description; private Object data; public HResponse () {} public HResponse (int status, String description, Object data) {this.status = status; this.description = description; this.data = data } public static HResponse success () {return new HResponse (200, "Operation successful", null);} public static HResponse success (String description) {return new HResponse (200, description, null);} public static HResponse success (Object data) {return new HResponse (200, "success", data);} public static HResponse success (String description, Object data) {return new HResponse (200, description, data) } public static HResponse error (String description) {return new HResponse (400, description, null);} public static HResponse error (String description, Object data) {return new HResponse (400, description, data);} public int getStatus () {return status;} public void setStatus (int status) {this.status = status;} public Object getData () {return data } public void setData (Object data) {this.data = data;} public String getDescription () {return description;} public void setDescription (String description) {this.description = description;}} 3.1 Redis case
Use StringRedisTemplate to perform basic operations on Redis. Here we simply provide two operations: querying the key value of Redis and setting the key value of Redis. Add the code to CommonController as follows
Private final StringRedisTemplate redisTemplate; private final SqlSession sqlSession; public CommonController (StringRedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;} @ PostMapping ("/ getRedisValue") public HResponse getRedisValue (String key) {this.logger.info ("request to get the value of redis key: {}", key); return HResponse.success (new JSONObject (). FluentPut ("key", key) .fluentPut ("value", this.redisTemplate.opsForValue (). Get (key) } @ PostMapping ("/ setRedisValue") public HResponse getRedisValue (String key, String value) {if (StringUtils.isBlank (key)) {return HResponse.error ("key cannot be null");} if (StringUtils.isBlank (value)) {return HResponse.error ("value cannot be null") } this.logger.info ("request to set redis key to: {}", key, value); this.redisTemplate.opsForValue () .set (key.trim (), value.trim ()); return HResponse.success ();}
Start the docker container of redis and run the current case. Use Postman to send request settings and query the corresponding key values in redis. The request response is shown below.
3.2 MySQL case
This paper briefly introduces two cases of querying data from MySQL, JPA mode and MyBatis mode. Start the docker container of MySQL first, then create the table h_company and insert a piece of data. The final result of the data table is as follows:
3.2.1 JPA mode
Construct the HCompany database mapping class and the corresponding database table access interface CompanyRepository, as follows:
@ Entity@Table (name = "h_company") @ Where (clause = "id > 0") public class HCompany {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Integer id; private String name; private String shortName; private String address; private String tel; private String remark; public Integer getId () {return id;} public void setId (Integer id) {this.id = id } public String getName () {return name;} public void setName (String name) {this.name = name;} public String getShortName () {return shortName;} public void setShortName (String shortName) {this.shortName = shortName;} public String getAddress () {return address;} public void setAddress (String address) {this.address = address } public String getTel () {return tel;} public void setTel (String tel) {this.tel = tel;} public String getRemark () {return remark;} public void setRemark (String remark) {this.remark = remark;}} @ Repository@Where (clause = "id > 0") public interface CompanyRepository extends PagingAndSortingRepository, JpaRepository {}
Add a method to query the database using CompanyRepository in the controller CommonController:
PostMapping ("/ getAllCompany") public HResponse getAllCompany () {return HResponse.success (this.companyRepository.findAll ());}
Use Postman to invoke the query with the following response
3.2.2 MyBatis mode
Use the SqlSession interface to access the database and create a company.xmlmapper file, as follows
Select * from h_company
Add a method to get data through MyBatis in the controller CommonController, as follows
PostMapping ("/ getAllCompanyByMybatis") public HResponse getAllCompanyByMybatis () {return HResponse.success (this.sqlSession.selectList ("company.getAll"));}
Restart the project and access it through Postman with the following response:
3.3 complete controller code
After completing the above steps, the complete content of the controller CommonController is as follows:
@ RestController@RequestMapping ("/ common") public class CommonController {private Logger logger = LoggerFactory.getLogger (this.getClass ()); private final StringRedisTemplate redisTemplate; private final CompanyRepository companyRepository; private final SqlSession sqlSession; public CommonController (StringRedisTemplate redisTemplate, CompanyRepository companyRepository, SqlSession sqlSession) {this.redisTemplate = redisTemplate; this.companyRepository = companyRepository; this.sqlSession = sqlSession } @ PostMapping ("/ getRedisValue") public HResponse getRedisValue (String key) {this.logger.info ("request to get the value of redis key: {}", key); return HResponse.success (new JSONObject () .fluentPut ("key", key) .fluentPut ("value", this.redisTemplate.opsForValue () .get (key) } @ PostMapping ("/ setRedisValue") public HResponse getRedisValue (String key, String value) {if (StringUtils.isBlank (key)) {return HResponse.error ("key cannot be null");} if (StringUtils.isBlank (value)) {return HResponse.error ("value cannot be null") } this.logger.info ("request to set redis key to: {}", key, value); this.redisTemplate.opsForValue () .set (key.trim (), value.trim ()); return HResponse.success ();} @ PostMapping ("/ getAllCompany") public HResponse getAllCompany () {return HResponse.success (this.companyRepository.findAll ()) } @ PostMapping ("/ getAllCompanyByMybatis") public HResponse getAllCompanyByMybatis () {return HResponse.success (this.sqlSession.selectList ("company.getAll"));}} 4 Health Monitoring
The case enables complete project monitoring, which can be viewed through http://localhost:9080/actuator, with each monitoring item corresponding to the corresponding view link, as shown in the following figure.
5 Project structure
After completing the above configuration and case, the project structure is as follows:
These are all the contents of the article "how to initialize background projects from scratch in Idea in Spring Boot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.