目录
数据库型
application-dev.yml 修改前
某些环境,不包括操作数据库的模块,但又不想把 pom 里的相关引用给去掉。
# 其它配置省略
spring:
data:
mongodb:
uri: mongodb://127.0.0.1:27017/test?connectTimeoutMS=300000
datasource:
url: jdbc:mysql://127.0.0.1:3306/vipsoft?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: 110
redis:
database: 11
host: 127.0.0.1
pool: 6379
password: 110
application-dev.yml 修改后
如下(修改后) -- 不使用MySQL、Redis、MongoDB
spring:
autoconfigure:
exclude:
# 排除 MongoDB 自动配置,否则会报 Exception in monitor thread while connecting to server localhost:27017
- org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
- org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration
@Service
public class MonitoringServiceImpl implements IMonitoringService {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired(required = false) //改成非必须,否则启动时会报错
private MongoTemplate mongoTemplate;
@Autowired //Redis 倒不受影响
RedisTemplate redisTemplate;
//.......
}
启动项目时,MySQL 报错
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (the profiles dev are currently active).
解决方案: 添加 DruidConfig : https://www.cnblogs.com/vipsoft/p/18489354#config-配置
这时就可以把 datasource:的配置移除了
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
//没设URL,就直接new 这时候启动不会报错
if (StrUtil.isEmpty(properties.getUrl())) {
return new DruidDataSource();
}
return properties
.initializeDataSourceBuilder()
.type(DruidDataSource.class)
.build();
}
其它组件
比如:在集群模式下,我想用 Nacos 组件,单机版不想用它。
server:
name: VipSoft Server Dev
port: 8193
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #注册中心地址(集群用,号分隔)
cluster-name: DEFAULT #可以通过集群名称区分不同的项目
server-name: netty-service
group-name: NETTY_GROUP
@Component
public class NettyServer {
private static final Logger logger = LoggerFactory.getLogger(LoggerConfig.NETTY_LOGGER);
@Value("${server.cloud.nacos.discovery.server-addr}")
private String nacosServer;
@Value("${server.cloud.nacos.discovery.server-name}")
private String serviceName;
@Value("${server.cloud.nacos.discovery.group-name}")
private String groupName;
}
@Component
public class XXXService {
@Autowired
private NacosUtil nacosUtil;
}
解决方案
方案1:使用条件注解 + 配置开关
- 修改 application.yml 添加启用开关:
server:
name: Telemetry Cloud Server Dev
port: 8193
cloud:
nacos:
enabled: false # 添加这个开关
discovery:
server-addr: 127.0.0.1:8848
cluster-name: DEFAULT
server-name: netty-service
group-name: NETTY_GROUP
- 修改 NettyServer 类:
@Component
@ConditionalOnProperty(name = "server.cloud.nacos.enabled", havingValue = "true")
public class NettyServer {
// 原有代码...
}
@Component
public class XXXService {
// 允许依赖不存在
@Autowired(required = false)
private NacosUtil nacosUtil;
}
方案2:使用 Profile 区分
- 创建不同环境的配置文件:
- application.yml (公共配置)
- application-nacos.yml (Nacos相关配置)
- application-standalone.yml (单机版配置)
- application.yml 中激活不同配置:
spring:
profiles:
active: standalone # 或 nacos
- 将 Nacos 相关配置移到 application-nacos.yml 中
方案3:编程式条件加载(更灵活)
- 添加配置开关:
netty:
mode: standalone # 或 cloud
- 创建配置类:
@Configuration
public class NettyConfig {
@Bean
@ConditionalOnProperty(name = "netty.mode", havingValue = "cloud")
public NettyServer nettyServer() {
return new NettyServer();
}
}
方案4:使用 @ConfigurationProperties 更优雅地管理配置
- 创建配置类:
@ConfigurationProperties(prefix = "server.cloud.nacos.discovery")
public class NacosProperties {
private boolean enabled;
private String serverAddr;
private String clusterName;
private String serverName;
private String groupName;
// getters and setters
}
- 修改 NettyServer:
@Component
public class NettyServer {
private final NacosProperties nacosProperties;
public NettyServer(NacosProperties nacosProperties) {
this.nacosProperties = nacosProperties;
if(nacosProperties.isEnabled()) {
// 初始化Nacos相关逻辑
}
}
}
最佳实践建议:
推荐方案1或方案4:
- 如果只是简单开关,用方案1最简单:
server:
cloud:
nacos:
enabled: false
@Component
@ConditionalOnProperty(name = "server.cloud.nacos.enabled", matchIfMissing = false)
public class NettyServer {
// ...
}
- 如果需要更复杂的配置管理,用方案4更优雅。
这样你可以通过修改配置文件的 enabled
值来决定是否启用Nacos相关功能,无需修改代码。