首页 » 脚本文章 » 分析加载过程(自定义加载过程分析配置)「加载项分析工具库」

分析加载过程(自定义加载过程分析配置)「加载项分析工具库」

admin 2024-07-23 19:43:07 脚本文章 0

扫一扫用手机浏览

文章目录 [+]

pom.xml文件依赖如下:

<dependencies> <dependency> <groupId>com.yanxin</groupId> <artifactId>myhello-spring-boot-autoconfigurer</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>复制代码

第二个项目工程,自动配置包

分析加载过程(自定义加载过程分析配置) 分析加载过程(自定义加载过程分析配置) 脚本文章
(图片来自网络侵删)

​ pom.xml文件依赖如下:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>复制代码

分析加载过程(自定义加载过程分析配置) 分析加载过程(自定义加载过程分析配置) 脚本文章
(图片来自网络侵删)
第二步,为自动配置包加入自动配置

先考虑这样一个组件,这个组件中的方法需要调用另一个组件的某些属性,我们想springboot运行的时候会自动配置这个组件。
利用组件来绑定属性,我们可以先写出这个类:

@ConfigurationProperties(prefix = "hello")public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; }}复制代码

其中@ConfigurationProperties注解用来将配置文件的配置和类绑定起来。

我们需要的功能组件类如下:

public class HelloService { HelloProperties hello; public HelloProperties getHello() { return hello; } public void setHello(HelloProperties hello) { this.hello = hello; } public String sayHello(String name){ String reply = hello.getPrefix() + name + hello.getSuffix(); System.out.println(reply); return reply; }}复制代码

我们给HelloProperties属性加上setter和getter方法就是为了可以给功能组件注入HelloProperties属性值。

自动配置类如下:

@Configuration@ConditionalOnWebApplication@EnableConfigurationProperties(HelloProperties.class)public class HelloAutoConfiguration { @Autowired HelloProperties hello; @Bean public HelloService getService(){ HelloService ser = new HelloService(); ser.setHello(hello); return ser; }}复制代码

自动配置类有@Configuration注解,可以自动加载该类到容器中(那么,springboot程序何时加载HelloAutoConfiguration类呢?)

在/META-INF/spring.factories中配置好,以便读取自动配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.yanxin.myhellospringbootautoconfigurer.HelloAutoConfiguration复制代码

将其导入maven仓库中,分别对两个module进行maven,install。

第三步,新建一个web项目,引用自定义starter

新建test-starter module,pom.xml文件引入

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.yanxin</groupId> <artifactId>myhello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>

标签:

相关文章