Starter is the wing of spring boot. If you insert the wings, you can fly very high~
Students who want to fly, follow me and DIY their own starter step by step~
1. Create POM project
Create a POM project named sayhello spring boot starter and introduce two dependencies, as shown in the figure:
2. Create bean
SayHello.java
package bean;
public class SayHello {
//There is only one attribute
private String name;
public void setName(String name){
this.name = name;
}
//Last output information
public String getMsg(){
return name + "say hello~~";
}
}
3. Create the properties class
SayHelloProperties.java
package properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
//Read the configuration of Hello: name in the configuration file
@ConfigurationProperties(prefix = "hello")
public class SayHelloProperties {
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
4. Create automatic configuration class
MyAutoConfiguration.java
@Configuration
@ConditionalOnClass(SayHello.class)
@EnableConfigurationProperties(SayHelloProperties.class)
public class MyAutoConfiguration {
@Autowired
SayHelloProperties sayHelloProperties;
@Bean
@ConditionalOnMissingBean(SayHello.class)
public SayHello getSayHiService(){
SayHello sayHello = new SayHello();
//Get the name from the configuration file. The bean sayhello is initialized
sayHello.setName(sayHelloProperties.getName());
return sayHello;
}
}
After reading the chapter on the principle of automatic configuration, the code looks very simple~
5. Create spring factories
In the resources / meta-inf directory, create spring.inf The contents of the factories file are automatic configuration classes
spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration= MyAutoConfiguration
When the project starts, you can automatically assemble myautoconfiguration
The overall structure of the project is as follows:
6. Maven packaging project
Package the project with the command MVN clean install to get the jar package sayhello-spring-boot-starter-1.0-snapshot jar
Next, you can upload the jar package to Maven private server or import it into another project by importing. Here, the latter is used. Operate in another project:
7. Configure Hello: name value
server:
port: 9000
hello:
name: wangdaye-
8. Create test controller
TestController.java
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
SayHello sayHello;
@GetMapping("/hello")
public String hello(){
return sayHello.getMsg();
}
}
Visit localhost: 9000 / test / Hello from the browser
Uncle Wang said hello to you, see~~