随着Spring框架的流行,在web服务器端的开发,Spring几乎成了开发的标准。但是随着开发的业务越来越复杂,分布式微服务的出现。基于SpringBoot开发在web服务端以及分布式微服务应用中,SpringBoot和基于SpringBoot的SpringCloud等也已经成为了主流。
SpringBoot的特点
@SpringBootApplication的组成
public interface HelloInterface {
void hello();
}
public class HelloImpl implements HelloInterface{
@Autowired
private HelloProperties helloProperties;
public void hello() {
System.out.println(helloProperties.getName()+" hello World");
}
}
@Component
@ConfigurationProperties("spring.zzz")
public class HelloProperties {
private String name = "zzz";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Configuration
@ConditionalOnClass
@EnableConfigurationProperties(HelloProperties.class)
public class MyTestStartAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public HelloImpl getHello(){
return new HelloImpl();
}
}
在pom文件中我们需要添加
至此一个starter创建完成。
将该项目打成jar包。
在另一个项目中引用。
引入成功
测试:
启动项目
该值为默认值,我们通过在application.properties修改name为zhangsan
由此就实现了通过在配置文件中修改值,就可以将start中的初始值改变,这也是为什么可以通过server.port可以配置服务器的端口,为什么可以通过配置集成jdbc、redis等。
对于Springboot的自动装配,通过@SpringBootApplication注解的分析,引出EnableAutoConfiguration注解,从而如何自定义一个starter。通过starter的这种方式,我们可以看到SpringBoot的这种可定制化可插拔式的好处,代码解耦方面体现淋漓尽致。
因篇幅问题不能全部显示,请点此查看更多更全内容