Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the concept and function of Spring Boot

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "introduction to the concept and function of Spring Boot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Spring Boot Learning Notes 1. Spring Boot Overview the birth of 1.Spring Boot

The purpose of Spring Boot is to improve and optimize the shortcomings of spring. Based on convention and superior to configuration, developers do not have to switch between configuration and business logic, and devote themselves to the coding of business logic, thus greatly improving development efficiency and shortening the project cycle.

Characteristics of 2.Spring Boot

Spring-based development provides a faster getting started experience

Right out of the box, no code generation, no XML configuration. You can modify the default configuration to meet specific needs

Provides some common non-functional features in large projects, such as embedded server, security, indicators, sound monitoring, external configuration, etc.

Spring Boot is not an enhancement to spring, but provides a quick way to use spring

Core functions of 3.Spring Boot

Start dependence

It is essentially a Maven project object model (Project Object Model,POM) that defines transitive dependencies on other libraries that, taken together, can support an energy. To put it simply, it is to package the coordinates with certain functions together and provide some default functions.

Automatic configuration

In essence, during the startup of the application, many factors are taken into account before deciding which spring configuration should be used, which is done automatically by spring.

Second, getting started with Spring Boot (1). The environment is built at 1:1. Create a common Maven project 2. Import startup dependency in pom.xml: springboot startup dependence and web startup dependence on org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE org.springframework.boot spring-boot-starter-web 3. 5. Write the boot class of the application

You need to start the springboot project through springboot's boot class before you can access it in the browser.

Package com.wsc;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * springboot boot class, program entry * / @ SpringBootApplicationpublic class MySpringBootApplication {public static void main (String [] args) {SpringApplication.run (MySpringBootApplication.class);}} 4. Write controller

Create a controller in the sibling package or subpackage of springboot's bootstrap class MySpringBootApplication

The controller of package com.wsc.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/** * springmvc * / @ Controllerpublic class QuickStartController {@ RequestMapping ("/ quick") @ ResponseBody public String quickStart () {return "spring boot is started." ; 5. test

Start the boot class and access http://localhost:8080/quick in the browser

The successful test shows that 2:idea creates the maven project as follows-> Select Spring Initializr-- > Click next-- > modify Project Matadata parameters-> next-- > Select the corresponding dependency and springboot version-> next check project name-> finish (2). Code Analysis of starter Program

@ SpringBootApplication: label this class as the startup class of SpringBoot, which has a variety of functions

SpringApplication.run (MySpringBootApplication.class) represents the startup class running SpringBoot, and the parameter is the bytecode object of the SpringBoot startup class.

(3)。 Set up springboot hot deployment 1. The concept of hot deployment

Set the hot deployment of springboot in idea, so that if we modify the resources such as classes, pages, etc., the code can take effect without restarting the server.

two。 Mode of realization

Just add the following configuration to pom.xml

Org.springframework.boot spring-boot-devtools

Note: the reason why IDEA failed to deploy SpringBoot is not due to the configuration problem of hot deployment. The root cause is that Intellij IEDA does not compile automatically by default, so automatic compilation of IDEA feeds is required, as shown below:

First go to file- > setting

Then Shift+Ctrl+Alt+/, chooses Registry

Third, the analysis of Spring Boot principle.

Start dependence: click on the jar package that you start to rely on to see the source code parsing. There are a lot of jar package dependencies in it.

Auto configuration: check the source code of @ SpringBootApplication, which integrates a lot of spring configurations

Fourth, the configuration file of Spring Boot (1). Type of Spring Boot configuration file

Springboot is convention-based, and many configurations have default values, but if you want to replace the default configuration with your own configuration, you can use application.properties or application.yml (application.yaml) for configuration.

Springboot loads application.properties or application.yml (application.yaml) files from the Resources directory by default

1. Application.properties# modifies the port number of the server server.port=8081# modifies the name of the web application server.servlet.context-path=/demo2.application.yml (equivalent to application.yaml) # configuration of ordinary data name: configuration of zhansan# object person: name: lisi age: 18 addr: configuration of beijing# object # person: {name: zhansan,age: 18 Addr: beijing} # configuration array, collection collection (normal string) city:-beijing-tianjiang-shanghai-shenzhencity2: [beijing,tianjing,shanhai,shenzhen] # configuration array, collection collection (object data) student:-name: zhansan age: 12 addr: beijing-name: lisi age: 13 addr: shenzhenstudent2: [{name: zhangsan,age: 12 shenzhenstudent2 addr: beijing}, {name: lisi,age: 14 Addr: shenzhen}] # configure the map collection map: key1: value1 key2: value2server: port: 8082 (2). Mapping relationship between configuration file and configuration class

How to inject the value of the property from the configuration file into the corresponding member of the configuration class.

1. Use @ Value@Controllerpublic class QuickController2 {@ Value ("${name}") / / to add @ Value annotations directly to members without get, set method private String name; @ Value ("${person.addr}") private String addr; @ RequestMapping ("/ quick2") @ ResponseBody public String quick2 () {return "name:" + name+ ", addr:" + addr;}} 2. Use the annotation @ ConfigurationProperties@Controller@ConfigurationProperties (prefix = "person") / / to add @ ConfigurationPropertiespublic class QuickController3 {private String name; private String addr; / / the get corresponding to the attribute that must be added, the set method public String getName () {return name;} public void setName (String name) {this.name = name;} public String getAddr () {return addr } public void setAddr (String addr) {this.addr = addr;} @ RequestMapping ("/ quick3") @ ResponseBody public String quick3 () {return "name:" + name+ ", addr:" + addr;}} V. Spring Boot integrates other technologies (1) .Spring Boot integrates Spring MVC

Add the initial dependency of web function to pom.xml, and the underlying layer passes the dependency of springmvc.

Org.springframework.boot spring-boot-starter-web (2). Spring Boot integrates Spring

Springboot does not enhance the functionality of spring, but provides a quick way to use spring

The start of springboot's parent project depends on the integration of spring and default configuration optimization of spring.

(3). Spring Boot integrates Mybatis

The integration steps are as follows:

1. Add mybatis's start-up dependence (pom.xml) org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.02. Add database-driven coordinates (pom.xml) mysql mysql-connector-java3. Add database connection information (resources/application.properties) # DB Configuration:spring.datasource.driverClassName=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=falsespring.datasource.username=rootspring.datasource.password=root4. Create a user table

Create the user table in the test database

-- Table structure for `user`-DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (`id` INT (11) NOT NULL AUTO_INCREMENT, `username` VARCHAR (50) DEFAULT NULL, `password` VARCHAR (50) DEFAULT NULL, `name` VARCHAR (50) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 -Records of user-- INSERT INTO `user`VALUES ('1x, 'zhangsan',' 123, 'Zhang San'); INSERT INTO `user`VALUES ('2x, 'lisi',' 123,'Li Si'); 5. Add entity class Beanpackage com.wsc.domain;import org.springframework.web.bind.annotation.InitBinder;public class User {private Integer id; private String username; private String password; private String name; / / getter setter. @ Override public String toString () {return "User {" + "id=" + id + ", username='" + username +'\'+ ", password='" + password +'\'+ ", name='" + name +'\'+'}';} 6. Write Mapper (equivalent to Dao) package com.wsc.mapper;import com.wsc.domain.User;import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper / / @ Mapper tag this class is a mybatis mapper interface that can be automatically scanned by spring boot into the spring context public interface UserMapper {public List queryUserList ();} 7. Configure the Mapper mapping profile (application.properties is equivalent to the main profile, to which you need to add a mapping profile)

Create a directory under src-- > main-- > resources > create a UserMapper.xml under mapper, which is as follows

Select * from user 8. Add mybatis information to application.properties, add mapping profile

The aim is to associate springboot with mybatis

# spring integrated Mybatis environment # pojo alias scan package mybatis.type-aliases-package=com.itheima.domain# loads the Mybatis mapping file mybatis.mapper-locations=classpath:mapper/*Mapper.xml9. Writing controllerpackage com.wsc.controller;import java.util.List;@Controllerpublic class MybatisController {@ Autowired private UserMapper userMapper;//userMapper will report an error at compile time, because the project cannot automatically generate mapper @ RequestMapping ("/ query") @ ResponseBody public List queryUserList () {return userMapper.queryUserList ();} @ RequestMapping ("/ test") @ ResponseBody public String testMybatis () {return "Integrated mybatis Framework";}} 10. Test access to browser http://localhost:8080/query(4).SpringBoot integration Junit1. The starting dependence of test function is automatically generated when it is created with idea. If not, the starting point of manually importing test function in pom.xml depends on org.springframework.boot spring-boot-starter-test test2. Write test class package com.wsc;import com.wsc.domain.User;import com.wsc.mapper.UserMapper;import java.util.List;/** * springbooot unit test * / @ RunWith (SpringRunner.class) / / who runs springboot's boot class @ SpringBootTest (classes = SpringbootMybatisApplication.class) / / Test the bytecode public class MybatisTest {@ Autowired private UserMapper userMapper; @ Test public void testQueryUserList () {List users = userMapper.queryUserList () of the boot class. System.out.println (users);}} (5). Spring Boot integrates Spring Data JPA1. Add spring data jpa's start-up dependence (pom.xml) org.springframework.boot spring-boot-starter-data-jpa 2. Add database-driven coordinates (pom.xml) mysql mysql-connector-java3. Add database connection information (resources/application.properties) # DB Configuration:spring.datasource.driverClassName=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=falsespring.datasource.username=rootspring.datasource.password=root4. Create a user table

Create the user table in the test database

-- Table structure for `user`-DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (`id` INT (11) NOT NULL AUTO_INCREMENT, `username` VARCHAR (50) DEFAULT NULL, `password` VARCHAR (50) DEFAULT NULL, `name` VARCHAR (50) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 -Records of user-- INSERT INTO `user`VALUES ('1x, 'zhangsan',' 123, 'Zhang San'); INSERT INTO `user`VALUES ('2x, 'lisi',' 123,'Li Si'); 5. Add entity class Beanpackage com.wsc.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class User {@ Id// primary key @ GeneratedValue (strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String name; public Long getId () {return id;} public void setId (Long id) {this.id = id } / / get set method. @ Override public String toString () {return "User {" + "id=" + id + ", username='" + username +'\'+ ", password='" + password +'\'+ ", name='" + name +'\'+'}';} 6. Writing Repository (equivalent to Dao and Mapper) package com.wsc.repository;import com.wsc.domain.User;import org.springframework.data.jpa.repository.JpaRepository;import java.util.List;/** * is equivalent to mapper and dao * / public interface UserRepository extends JpaRepository {public List findAll ();} 7. Integrate springdata jpa information in application.properties # springboot integrate springdata jpa#JPA Configuration:spring.jpa.database=MySQLspring.jpa.show-sql=truespring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto=updatespring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy9. Write the test class package com.wsc;@RunWith (SpringRunner.class) @ SpringBootTest (classes = SpringbootDataJpaApplication.class) public class SpringDataJpaTest {@ Autowired private UserRepository userRepository; @ Test public void testFindAll () {List all = userRepository.findAll (); System.out.println (all);}} 10. Unit test console output:

Note: jdk9 needs to import dependencies manually

Javax.xml.bind jaxb-api 2.3.0 (6). Spring Boot Integration Spring Cloud (7). Spring Boot Integration Redis1. Add redis's start-up dependence (pom.xml) org.springframework.boot spring-boot-starter-data-redis2. Configure the connection information of redis in application.properties # Redisspring.redis.host=127.0.0.1spring.redis.port=63793. Write test classes

Injecting RedisTemplate to test redis operation

Package com.wsc;@RunWith (SpringRunner.class) @ SpringBootTest (classes = SpringbootDataJpaApplication.class) public class RedisTest {@ Autowired private UserRepository userRepository; @ Autowired private RedisTemplate redisTemplate; () throws JsonProcessingException {/ / 1. Query String userListJson = redisTemplate.boundValueOps ("user.findAll") .get () from redis; / / 2. If not in redis, query if (null==userListJson) {/ / 3 from the database. Query List all = userRepository.findAll () from the database; / / 4. Serialize list objects to json string jackson parsing engine ObjectMapper objectMapper = new ObjectMapper (); userListJson = objectMapper.writeValueAsString (all); / / 5. Store json strings in redis redisTemplate.boundValueOps ("user.findAll") .set (userListJson); System.out.println ("= = query from database =");} else {System.out.println ("= query from redis =");} System.out.println (userListJson) This is the end of the introduction to the concept and function of Spring Boot. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report