在 Spring Boot 2 中,可以通过以下步骤解决 Cloud 无法绑定属性到 serverProperties 的问题:\n\n1. 确保你的项目中已经添加了必要的依赖,包括spring-boot-starter-webspring-cloud-starter。\n2. 在 application.properties 或 application.yml 文件中添加以下属性:\n\n\nserver:\n address: localhost\n port: 8080\n\n\n3. 创建一个自定义的 ServerProperties 类,用于绑定 server 相关的属性:\n\njava\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n@ConfigurationProperties(prefix = "server")\npublic class MyServerProperties {\n private String address;\n private int port;\n\n // 添加 getter 和 setter 方法\n\n // 如果需要自定义其他属性,可以在这里添加\n}\n\n\n4. 在主应用程序类中使用@EnableConfigurationProperties注解启用自定义的 ServerProperties 类:\n\njava\n@SpringBootApplication\n@EnableConfigurationProperties(MyServerProperties.class)\npublic class Application {\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n\n\n5. 在需要使用 server 属性的地方,注入 MyServerProperties 类,并使用其中的属性:\n\njava\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class MyComponent {\n @Autowired\n private MyServerProperties serverProperties;\n\n public void printServerProperties() {\n System.out.println("Address: " + serverProperties.getAddress());\n System.out.println("Port: " + serverProperties.getPort());\n }\n}\n\n\n通过以上步骤,你可以成功绑定 Cloud 属性到 serverProperties 类中,并在其他组件中使用。


原文地址: http://www.cveoy.top/t/topic/pNre 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录