For example: In cluster mode, I want to use Nacos components, but I don't want to use it on the stand-alone version.
server:
name: VipSoft Server Dev
port: 8193
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #Register center address (separated by clusters)
cluster-name: DEFAULT #Can distinguish different projects by cluster name
server-name: netty-service
group-name: NETTY_GROUP
@Component
public class NettyServer {
private static final Logger logger = (LoggerConfig.NETTY_LOGGER);
@Value("${-addr}")
private String nacosServer;
@Value("${-name}")
private String serviceName;
@Value("${-name}")
private String groupName;
}
Solve the copy
Solution 1: Use condition annotations + configuration switch
- Modify Add Enable Switch:
server:
name: Telemetry Cloud Server Dev
port: 8193
cloud:
nacos:
enabled: false # Add this switch
discovery:
server-addr: 127.0.0.1:8848
cluster-name: DEFAULT
server-name: netty-service
group-name: NETTY_GROUP
- Modify the NettyServer class:
@Component
@ConditionalOnProperty(name = "", havingValue = "true")
public class NettyServer {
// Original code...
}
Solution 2: Use Profile to distinguish
- Create configuration files for different environments:
- (Public configuration)
- (Nacos related configuration)
- (Standalone version configuration)
- Activate different configurations:
spring:
Profiles:
active: standalone # or nacos
- Move Nacos-related configurations to
Solution 3: Programming conditional loading (more flexible)
- Add configuration switch:
netty:
mode: standalone # or cloud
- Create a configuration class:
@Configuration
public class NettyConfig {
@Bean
@ConditionalOnProperty(name = "", havingValue = "cloud")
public NettyServer nettyServer() {
return new NettyServer();
}
}
Solution 4: Use @ConfigurationProperties to manage configuration more elegantly
- Create a configuration class:
@ConfigurationProperties(prefix = "")
public class NacosProperties {
private boolean enabled;
private String serverAddr;
private String clusterName;
private String serverName;
private String groupName;
// getters and setters
}
- Modify NettyServer:
@Component
public class NettyServer {
private final NacosProperties nacosProperties;
public NettyServer(NacosProperties nacosProperties) {
= nacosProperties;
if(()) {
// Initialize Nacos related logic
}
}
}
Best Practice Recommendations:
Recommended Plan 1 or Plan 4:
- If it's just a simple switch, use solution 1 is the easiest:
server:
cloud:
nacos:
enabled: false
@Component
@ConditionalOnProperty(name = "", matchIfMissing = false)
public class NettyServer {
// ...
}
- If more complex configuration management is needed, use Solution 4 is more elegant.
This way you can modify the configuration fileenabled
Value to determine whether to enable Nacos-related functions without modifying the code.