1、添加依賴
<dependencies>
<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-autoconfigure</artifactId>
</dependency>
</dependencies>
2、配置文件讀取類
@ConfigurationProperties(prefix = "gefs.socketio")
@Data
public class SocketioProperties {
private boolean enabled;
private String host;
private int port;
}
3、編寫AutoConfigure類
@org.springframework.context.annotation.Configuration
@EnableConfigurationProperties(SocketioProperties.class)
@ConditionalOnProperty(prefix = "gefs.socketio", name = "enabled", havingValue = "true")
public class SocketioAutoConfiguration {
@Autowired
private SocketioProperties socketioProperties;
@Bean
public SocketIOServer socketIOServer() {
Configuration config = new Configuration();
//在本地window環境測試時用localhost
config.setHostname(socketioProperties.getHost());
config.setPort(socketioProperties.getPort());
SocketIOServer server = new SocketIOServer(config);
server.start();
return server;
}
@Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
}
}
4、在resources/META-INF/下創建spring.factories文件並編寫內容
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.aostarit.gefs.socketio.SocketioAutoConfiguration
5、編譯代碼(增加配置文件自動提示)
將編譯好的target\classes\META-INF/spring-configuration-metadata.json文件拷貝至resources/META-INF/