spring-boot-starter简介 解决@Configuration中@value无值问题

spring-boot 在配置上相比spring要简单许多, 其核心在于spring-boot-starter, 在使用spring-boot来搭建一个项目时, 只需要引入官方提供的starter, 就可以直接使用, 免去了各种配置, 原因在于spring-boot的自动发现,比如当classpath下面有tomcat-embedded.jar 时,对应的bean就会被加载.下面会介绍如何自己写一个简单的starter,并在自己的工程中使用这个starter
新建一个maven project结构如下:
在这里插入图片描述
其中GreetorService是我们要提供给外部使用的bean, GreetorProperties包含了这个bean需要的信息, GreetorAutoConfiguration负责提供这个bean
下面依次看一下各个class

public class GreetorService {

    private GreetorProperties properties;

    public GreetorService(GreetorProperties properties) {
        this.properties = properties;
    }

    public String greet() {
        return "greet by" + properties.getName() + " msg " + properties.getMsg();
    }

}

GreetorService , 一个简单的service

@ConfigurationProperties(prefix="greetor")
public class GreetorProperties {

    private String name;
    
    private String msg;
    
    public String getName() {
        return name;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}

properties bean, 会从application.properties 或 yml中把对应的properties映射到bean中

@ConditionalOnClass(GreetorService.class)
@EnableConfigurationProperties(GreetorProperties.class)
@Configuration
public class GreetorAutoConfiguration {
    
    @Autowired
    private GreetorProperties greetorProperties;
    
    @Bean
    @ConditionalOnMissingBean(GreetorService.class)
    public GreetorService greetorService() {
        return new GreetorService(greetorProperties);
    };
    
}

最为重要的class, @ConditionalOnClass 只有当特定的class在classpath上时, BeanDefination才会被注册, @ConditionalOnMissingBean 同理, @EnableConfigurationProperties 这个用于激活PropertyBean
在META-INF中新建一个名为spring.factories的文件 (下文介绍其作用),内容为

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.iplay.springtest.configuration.GreetorAutoConfiguration

最后看一下依赖

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.iplay.springtest</groupId>
    <artifactId>greeter-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>starter-greetor</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

之后我们新建另一个maven project, 并依赖我们刚才建立的starter
测试类 如下

@SpringBootApplication
public class StarterGreetorUsageApplication implements CommandLineRunner {

    @Autowired
    private GreetorService greetorService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(greetorService.greet());
    }

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

}

在application.properties中增加如下内容

greetor.name=test
greetor.msg=hello

运行application 可以看到以下信息
greet bytest msg hello
下面我们看一下为什么GreetorAutoConfiguration会得到处理
@SpringBootApplication 包含了@EnableAutoConfiguration, @EnableAutoConfiguration包含了@Import(AutoConfigurationImportSelector.class)
@Import可以接受一个ImportSelector
AutoAutoConfigurationImportSelectorImportSelector的实现
其中核心代码为

![在这里插入图片描述](https://img-blog.csdnimg.cn/2020022611134371.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzczODgzMA==,size_16,color_FFFFFF,t_70)

决定了哪些configuration会被import
在这里插入图片描述
这里调用了getCandidateConfigurations
在这里插入图片描述
SpringFactoriesLoader会从META-INF/spring.factories中读取对应的factory, 所以当我们启动项目时,会检查META-INF/spring.factories key为org.springframework.boot.autoconfigure.EnableAutoConfiguration的值.
在spring-boot-autoconfigure这个包中也包含了spring.factories, 部分值为下

在这里插入图片描述
对应了各个starter的autoconfiguration, 这些autoconfiguration使我们只需引入各个starter就能够快速搭建一个spring-boot app

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Spring Boot WebSocket 入门 demo: 1. 首先,在 pom.xml 文件引入 `spring-boot-starter-websocket` 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建一个简单的 WebSocket 处理器: ```java @Component public class WebSocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); session.sendMessage(new TextMessage("连接成功!")); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession webSocketSession : sessions) { webSocketSession.sendMessage(new TextMessage("客户端说:" + message.getPayload())); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } } ``` 3. 创建 WebSocket 配置类: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/ws").setAllowedOrigins("*"); } } ``` 4. 编写一个简单的页面来测试 WebSocket: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket</title> </head> <body> <h1>WebSocket Demo</h1> <div> <input type="text" id="input"/> <button onclick="send()">发送</button> </div> <div id="output"></div> <script> var socket = new WebSocket("ws://localhost:8080/ws"); socket.onmessage = function(event) { var output = document.getElementById("output"); output.innerHTML += "<p>" + event.data + "</p>"; }; function send() { var input = document.getElementById("input"); socket.send(input.value); input.value = ""; } </script> </body> </html> ``` 5. 运行程序,访问 http://localhost:8080/index.html,打开浏览器控制台,输入命令 `socket.send("Hello, WebSocket!")`,即可看到页面上显示出 "客户端说:Hello, WebSocket!"。 希望这个 demo 能帮助到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值