Spring Initializer in IDEA quickly creates a Spring Boot project
IDEs all support the use of Spring’s project creation wizard to quickly create a Spring Boot project;
select the module we need; the
wizard will create a Spring Boot project on the Internet; the
default generated Spring Boot project; the
main program has been generated, we only need our own Logic
The directory structure in the generated resources folder
- static: save all static resources; js css images;
- Templates: save all template pages; (Spring Boot default jar package uses embedded Tomcat, and JSP pages are not supported by default); template engines (freemarker, thymeleaf) can be used;
- application.properties: Spring Boot application configuration file; some default settings can be modified;
Configuration file
SpringBoot uses a global configuration file, the configuration file name is fixed; application.properties and application.yml
The role of the configuration file: modify the default value of SpringBoot automatic configuration; SpringBoot automatically configures us at the bottom;
Where the suffix name is yml, the full name is yaml
YAML (YAML Ain't Markup Language) can be understood as
YAML A Markup Language: is a markup language
or
YAML isn't Markup Language: not a markup language;
markup language:
previous configuration File; most of them use xxxx.xml file;
YAML: data-centric, more suitable for configuration files than json, xml, etc.;
YAML: configuration example
server:
port: 8081
The corresponding configuration example of the previous xml
<server>
<port>8081</port>
</server>
YAML syntax
Basic grammar
k: (space) v: represents a pair of key-value pairs (spaces must be present); the
hierarchical relationship is controlled by indentation of spaces; as long as a column of data is left-aligned, the
attributes and values of the same level are also case sensitive;
Value writing
-
Literal value: ordinary value (number, string, boolean)
k: v: write directly literally;
string default does not need to add single or double quotes;
"": double quotes; will not escape special characters in the string Characters; special characters will be what they want to express
name: "zhangsan \n lisi": output; zhangsan newline lisi
'': single quotation mark; special characters will be escaped, special characters are just a normal string data
name: ' zhangsan \n lisi': output; zhangsan \n lisi -
Object, Map (attributes and values) (key-value pairs)
k: v: write the relationship between the attributes and values of the object in the next line; note that the indentation
is still k: v
friends:
lastName: zhangsan
age: 20
Inline writing:
friends: {
lastName: zhangsan,age: 18}
- Array (List, Set)
uses-value to represent an element in the array
pets:
‐ cat
‐ dog
‐ pig
Inline writing
pets: [cat,dog,pig]
Profile injection
The first configuration file written is
person:
lastName: hello
age: 18
boss: false
birth: 2019/12/26
maps: {
k1: v1,k2: v2}
lists:
- lisi
- zhangsan
dog:
name: 狗
age: 12
The corresponding JavaBean is
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉springboot将本类中的所有的属性和配置文件中相关的配置进行绑定
* prefix = "person":以配置文件中哪个下面的所有属性进行一一映射
* 只有这个组件是容器的组件,才能让容器提供的@ConfigurationProperties功能
*/
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource("classpath:application.yaml")
public class Person
{
private String lastName;
private Integer age;
private boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
Test in the test unit
/**
* spring boot单元测试
* 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能
*/
@SpringBootTest
class TestApplicationTests
{
@Autowired
Person person;
@Test
void contextLoads()
{
System.out.println("================================================");
System.out.println(person);
}
}
result
Change to application.properties injection
person.last-name=小杨
person.age=18
person.birth=2020/12/26
person.boss=false
person.maps.v1=擎天柱
person.maps.v2=28
person.lists=1,2,3
person.dog.name=狗狗
person.dog.age=5
It's just that there will be Chinese garbled problems, refer to this article
Use @value to bind data
Previously, @ConfigurationProperties(prefix = "person") was used to bind the data in the configuration file. Now it is changed to @Value.
The role and usage of the Value in spring is the same.
Before using spring to configure the bean It was almost like this
<bean class="Person">
<property name="lastname" value=""></property>
</bean>
The current @Value is similar to the above value in usage, and it can also be written in denominations, $(key) takes the value from the environment variable, #{Spel} expression to get the result
@Value gets the value and @ConfigurationProperties gets the value
@ConfigurationProperties | @Value | |
Features | Bulk injection of properties in configuration files | Specify one by one |
Loose binding (loose syntax is the matching rule of attribute names, such as person.firstName: use the standard method, person.first-name: use uppercase, person.first_name: use _ for uppercase, the above three methods are considered in loose syntax They are the same variable) | stand by | not support |
SpEL (spring expression language) | not support | stand by |
JSR303 data verification | stand by | not support |
The biggest difference: complex type packaging, such as map packaging | stand by | not support |
If we just need to get a value in the configuration file in a certain business logic, use @Value; if we write a javaBean to map the configuration file, we will directly use @ConfigurationProperties;
JSR303 data verification is to verify whether the bound data meets the requirements when injecting them, such as whether it meets the email address.
Add @Validated and @email for verification
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person
{
@email
private String lastName;
private Integer age;
private boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
@PropertySource&@ImportResource&@Bean
@PropertySource
Load the specified configuration file; the
previously used @ConfigurationProperties(prefix = "") defaults to get the value from the global configuration file,
but if we write everything in the configuration file, the configuration file will have too much data, So we extract some of the JavaBean data and put it in other configuration files. At this time, we need to use this annotation to get the values in other configuration files.
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
@PropertySource(value = "classpath:person.properties")
public class Person
{
// @Value("哆啦A梦")
// @email
private String lastName;
// @Value("${person.age}")
private Integer age;
// @Value("#{1==1}")
private boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
@ImportResource
Import the Spring configuration file to make the content in the configuration file effective;
Spring Boot does not have a Spring configuration file, and the configuration file we wrote by ourselves cannot be automatically recognized; if
you want the Spring configuration file to take effect, load it in; @ImportResource is marked in A configuration class
now we want to add it directly to the main configuration class
@ImportResource(locations ={
"classpath:bean.xml"} )
@SpringBootApplication
public class TestApplication
{
public static void main(String[] args)
{
SpringApplication.run(TestApplication.class, args);
}
}
Spring configuration file bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="jane.test.bean.Dog"></bean>
</beans>
test
@Autowired
ApplicationContext ioc;
@Test
public void test()
{
boolean dog = ioc.containsBean("dog");
System.out.println(dog);
}
结果是true的
@Bean
In the above example, if you want to add components to the spring container, spring boot does not recommend writing a sprig configuration file and then loading it.
Spring boot recommends using the configuration class. This configuration class can be written separately or in the main On the configuration class,
this configuration class is equivalent to the previous spring configuration file
package jane.test.jane.config;
import jane.test.bean.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author jane
* @create 2020-08-05 1:48
*
* @Configuration:就是指明当前类是一个配置类,
* 就是用来替代之前的spring的配置文件
*/
@Configuration
public class Myconfig
{
//将方法中返回值添加到容器中,容器中的这个组件的默认的id就是方法名
@Bean
public Dog dog()
{
System.out.println("增加了一个狗");
return new Dog();
}
}
Placeholders in configuration files
random number
${
random.value}、${
random.int}、${
random.long}
${
random.int(10)}、${
random.int[1024,65536]}
The placeholder gets the previously configured value, if not, it can be used: specify the default value
person.last-name=小杨${
random.uuid}
person.age=${
random.int}
person.birth=2020/12/26
person.boss=false
person.maps.v1=擎天柱
person.maps.v2=28
person.lists=1,2,3
person.dog.name=${
person.last-name}的狗
person.dog.age=5