/** * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com). *
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
* http://www.gnu.org/licenses/lgpl.html *
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springblade.core.launch; import org.springblade.core.launch.constant.AppConstant; import org.springblade.core.launch.constant.NacosConstant; import org.springblade.core.launch.constant.SentinelConstant; import org.springblade.core.launch.service.LauncherService; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.*; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * 项目启动器,搞定环境变量问题 * * @author Chill */ public class BladeApplication { /** * Create an application context * java -jar app.jar --spring.profiles.active=prod --server.port=2333 * * @param appName application name * @param source The sources * @return an application context created from the current state */ public static ConfigurableApplicationContext run(String appName, Class source, String... args) { SpringApplicationBuilder builder = createSpringApplicationBuilder(appName, source, args); return builder.run(args); } public static SpringApplicationBuilder createSpringApplicationBuilder(String appName, Class source, String... args) { return createSpringApplicationBuilder(null,appName, source, args); } /** * 兼容tomcat等外部容器启动,使用此方法时请按照1进行工程改造 *
1-https://sns.bladex.cn/q-6813.html*
2-解决https://sns.bladex.cn/q-66.html问题* @param builder builder * @param appName appName * @param source source * @param args args * @return */ public static SpringApplicationBuilder createSpringApplicationBuilder(SpringApplicationBuilder builder,String appName, Class source, String... args){ Assert.hasText(appName, "[appName]服务名不能为空"); // 读取环境变量,使用spring boot的规则 ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); propertySources.addFirst(new SimpleCommandLinePropertySource(args)); propertySources.addLast(new MapPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, environment.getSystemProperties())); propertySources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, environment.getSystemEnvironment())); // 获取配置的环境变量 String[] activeProfiles = environment.getActiveProfiles(); // 判断环境:dev、test、prod List