精通Spring Boot——第五篇:写一个spring-boot-starter包

为了能更好的理解Springboot的自动配置和工做原理,咱们今天来手写一个spring-boot-hello-starter。这个过程很简单,代码很少。接下来咱们看看怎么开始实践。 ##1. 新建maven工程。 这块就不演示了,若是不会能够自行百度...啦啦啦,由于太简单了啊java

2.新建一个properties类

/**
 * @author Lee
 * @// TODO 2018/7/25-9:21
 * @description
 */
@ConfigurationProperties(prefix = "customer")
public class CustomerProperties {
    private static final String DEFAULT_NAME = "Lensen";

    private String name = DEFAULT_NAME;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.建立一个服务类CustomerServicegit

/**
 * @author Lee
 * @// TODO 2018/7/25-10:30
 * @description
 */
public class CustomerService {
    private String name;

    public String findCustomer(){
        return "The Customer is " + name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.AutoConfiguration类

/**
 * @author Lee
 * @// TODO 2018/7/25-10:32
 * @description
 */
@Configuration
@EnableConfigurationProperties(CustomerProperties.class)
@ConditionalOnClass(CustomerService.class)
@ConditionalOnProperty(prefix = "customer", value = "enabled", matchIfMissing = true)
public class CustomerAutoConfiguration {

    @Autowired
    private CustomerProperties customerProperties;

    @Bean
    @ConditionalOnMissingBean(CustomerService.class)
    public CustomerService customerService() {
        CustomerService customerService = new CustomerService();
        customerService.setName(customerProperties.getName());
        return customerService;
    }
}

##4. spring.factories配置github

在src/main/resources新建文件夹META-INF,而后新建一个spring.factories文件spring

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.developlee.configurer.CustomerAutoConfiguration

pom文件修改artifactId为spring-boot-hello-starter 打包成jar. 而后用mvn install 安装到本地mvn仓库。 ##5. 测试spring-boot-hello-start 新建springboot工程,在pom.xml文件引入安装的jar包springboot

<dependency>
		<groupId>com.developlee</groupId>
		<artifactId>spring-boot-hello-starter</artifactId>
		<version>1.0-SNAPSHOT</version>
	</dependency>

在项目启动类中直接作测试:app

@SpringBootApplication
@RestController
public class TestStarterApplication {

	@Autowired
	CustomerService customerService;

	@GetMapping("/")
	public String index(){
		return customerService.getName();
	}

	public static void main(String[] args) {
		SpringApplication.run(TestStarterApplication.class, args);
	}
}

application.properties文件配置下咱们的customer.namemaven

customer.name = BigBBrother

接下来启动项目,请求地址localhost:8080, 便可看到页面上显示BigBBrotherspring-boot

到这咱们已经完成了一个spring-boot-starter jar包的开发,有不少功能咱们能够本身封装成一个jar,之后要用直接引用就好了~ 这样写代码是否是会有不同的体验呢? 源代码在个人github能够找到哦测试

相关文章
相关标签/搜索