spring-boot引入mvn install打好包

怎么实现自己的starter?

原理浅谈

从总体上来看,无非就是将Jar包作为项目的依赖引入工程。而现在之所以增加了难度,是因为我们引入的是Spring Boot Starter,所以我们需要去了解Spring Boot对Spring Boot Starter的Jar包是如何加载的?下面我简单说一下。

SpringBoot 在启动时会去依赖的 starter 包中寻找 /META-INF/spring.factories 文件,然后根据文件中配置的路径去扫描项目所依赖的 Jar 包,这类似于 Java 的 SPI(JavaSPI 实际上是“基于接口的编程+策略模式+配置文件”组合实现的动态加载机制。) 机制。

实现自动配置

1.新建一个Spring Boot工程,命名为spring-boot-starter-hello,pom.xml依赖:


     org.springframework.boot
     spring-boot-starter-web

2.新建HelloProperties类,定义一个hello.msg参数(默认值World!)。

public class HelloProperties {
    private String msg = "World!";
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3.新建HelloService类,使用HelloProperties类的属性

@Service
public class HelloService {
    @Autowired
    private HelloProperties helloProperties;
    public String sayHello(String name) {
        return "Hello " + name + " " + helloProperties.getMsg();
    }
}

4.自动配置类,可以理解为实现自动配置功能的一个入口。

@Configuration //定义为配置类
@ConditionalOnWebApplication //在web工程条件下成立
@EnableConfigurationProperties({HelloProperties.class}) //启用HelloProperties配置功能,并加入到IOC容器中
@Import(HelloService.class) //导入HelloService组件
public class HelloAutoConfiguration {
}

5.在resources目录下新建META-INF目录,并在META-INF下新建spring.factories文件,写入:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.hanxing.spirngboot.HelloAutoConfiguration

6.项目到这里就差不多了,不过作为依赖,最好还是再做一下收尾工作

  • 删除自动生成的启动类SpringBootStarterHelloApplication
  • 删除resources下的除META-INF目录之外的所有文件目录
  • 删除spring-boot-starter-test依赖并且删除test目录
  • 执行mvn install将spring-boot-starter-hello安装到本地
2、随便新建一个Spring Boot工程,引入spring-boot-starter-hello依赖。

idea引入新的依赖,重新导入pom文件,如果找不到可能是mvn intall 到本地包的.m2文件里路径不对


  com.hanxing
  spring-boot-starter-hello
   0.0.1-SNAPSHOT

在新工程中使用spring-boot-starter-hello的sayHello功能。

@SpringBootApplication
@Controller
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Autowired
    private HelloService helloService;
    @RequestMapping(value = "/sayHello")
    @ResponseBody
    public String sayHello(String name) {
        System.out.println(helloService.sayHello(name));
        return helloService.sayHello(name);
    }
}

参考文档:https://www.jianshu.com/p/59dddcd424ad
解决中文乱码解决:https://www.cnblogs.com/yueshutong/p/10703561.html

你可能感兴趣的:(spring-boot引入mvn install打好包)