使用server 和client 配置文件从命令行启动
要对 2 个不同的配置文件使用相同的 jar 和相同的入口点,您只需在运行时提供 Spring 配置文件,以加载不同的 application-${profile}.properties(并可能触发条件 Java 配置)。
定义 2 个弹簧轮廓(client 和 server):
- 每个都有自己的
application-${profile}.properties
- 客户端的属性将禁用 Web 容器
只有一个 SpringBootApp 和入口点:
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.run(args);
}
}
让这个类成为你的主类。
src/main/resources/application-server.properties:
spring.application.name=server
server.port=8080
src/main/resources/application-client.properties:
spring.application.name=client
spring.main.web-environment=false
从命令行启动两个配置文件:
$ java -jar -Dspring.profiles.active=server YourApp.jar
$ java -jar -Dspring.profiles.active=client YourApp.jar
您也可以根据活动配置文件有条件地触发 @Configuration 类:
@Configuration
@Profile("client")
public class ClientConfig {
//...
}
使用 server 和 client 配置文件从 IDE 启动
发射器:
@SpringBootApplication
public class SpringBootApp {
}
public class LauncherServer {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.profiles("server")
.run(args);
}
}
public class ClientLauncher {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.profiles("client")
.web(false)
.run(args);
}
}
您可以指定其他配置类(特定于客户端或服务器):
new SpringApplicationBuilder()
.sources(SpringBootApp.class, ClientSpecificConfiguration.class)
.profiles("client")
.web(false)
.run(args);
src/main/resources/application-server.properties:
spring.application.name=server
server.port=8080
src/main/resources/application-client.properties:
spring.application.name=client
#server.port= in my example, the client is not a webapp
注意,您可能还有 2 个 SpringBootApp (ClientSpringBootApp,
ServerSpringBootApp),每个都有自己的 main,这是一个类似的设置
这允许您配置不同的AutoConfiguration 或ComponentScan:
@SpringBootApplication
@ComponentScan("...")
public class ServerSpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(ServerSpringBootApp.class)
.profiles("server")
.run(args);
}
}
//Example of a difference between client and server
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan("...")
public class ClientSpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(ClientSpringBootApp.class)
.profiles("client")
.web(false)
.run(args);
}
}