Spring Boot核心教程

SpringBoot非官方教程 | 第二十二篇: 创建含有多mo

2018-07-03  本文已影响75人  程序员手札

https://blog.csdn.net/forezp/article/details/70341818
本文出自方志朋的博客

这篇文章主要介绍如何在springboot中如何创建含有多个module的工程,栗子中含有两个 module,一个作为libarary. 工程,另外一个是主工程,调用libary .其中libary jar有一个服务,main工程调用这个服务。

创建根工程

创建一个maven 工程,其pom文件为:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.forezp</groupId>
    <artifactId>springboot-multi-module</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>springboot-multi-module</name>
    <description>Demo project for Spring Boot</description>

</project>

需要注意的是packaging标签为pom 属性。

创建libary工程

libary工程为maven工程,其pom文件的packaging标签为jar 属性。创建一个service组件,它读取配置文件的 service.message属性。

@ConfigurationProperties("service")
public class ServiceProperties {

    /**
     * A message for the service.
     */
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

提供一个对外暴露的方法:

@Configuration
@EnableConfigurationProperties(ServiceProperties.class)
public class ServiceConfiguration {
    @Bean
    public Service service(ServiceProperties properties) {
        return new Service(properties.getMessage());
    }
}

创建一个springbot工程

引入相应的依赖,创建一个web服务:

@SpringBootApplication
@Import(ServiceConfiguration.class)
@RestController
public class DemoApplication {

    private final Service service;

    @Autowired
    public DemoApplication(Service service) {
        this.service = service;
    }

    @GetMapping("/")
    public String home() {
        return service.message();
    }

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

在配置文件application.properties中加入:

service.message=Hello World

打开浏览器访问:http://localhost:8080/;浏览器显示:

Hello World

说明确实引用了libary中的方法。

参考资料

https://spring.io/guides/gs/multi-module/

源码下载

https://github.com/forezp/SpringBootLearning

写在最后

欢迎关注喜欢、和点赞后续将推出更多的spring cloud教程,敬请期待。
欢迎关注我的微信公众号获取更多更全的学习资源,视频资料,技术干货!

欢迎扫码关注

公众号回复“学习”,拉你进程序员技术讨论群。

公众号回复“视频”,领取800GJava视频学习资源。

java学习全套
820G资源

公众号回复“领取资源”,领取1T前端Java产品经理微信小程序Python等资源合集大放送。

全栈资料
接近1T资源

公众号回复“慕课”,领取1T慕课实战学习资源。

慕课实战大全
1061G资源

公众号回复“实战”,领取750G项目实战学习资源。

前后端实战项目
750实战资源

公众号回复“面试”,领取8G面试实战学习资源。

JAVA面试实战视频
8G面试资源
上一篇 下一篇

猜你喜欢

热点阅读