Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java environment.getProperty(“property”)是否生成与@value(“property”)相同的值_Java_Spring_Spring Boot - Fatal编程技术网

Java environment.getProperty(“property”)是否生成与@value(“property”)相同的值

Java environment.getProperty(“property”)是否生成与@value(“property”)相同的值,java,spring,spring-boot,Java,Spring,Spring Boot,我正在重构一个项目,在其中一个服务上我发现了这段代码: @Service public class MyService { private String API_PORT; public JenkinsService(final Environment environment) { this.API_PORT = environment.getProperty("server.port"); } } 我的疑问是,我是否可以将其更改为以下代码(使

我正在重构一个项目,在其中一个服务上我发现了这段代码:

@Service
public class MyService {   
    private String API_PORT;


    public JenkinsService(final Environment environment) {
        this.API_PORT = environment.getProperty("server.port");
    }
}
我的疑问是,我是否可以将其更改为以下代码(使用@Value),而不会出现意外行为:

@Service
public class MyService {   
    @Value("${server.port}")
    private String API_PORT;


    public JenkinsService() {}
}

${server.port}将有一个整数值

@值(“${server.port}”)
私有int API_端口

${server.PORT}将具有整数值

@值(“${server.port}”) 专用内部API_端口

TL;医生:是的

除非您对custom
PropertyPlaceholderResover执行奇怪的操作,否则这两个示例在默认的Spring引导应用程序中的操作将完全相同;医生:是的


除非您对custom
PropertyPlaceholderResover执行奇怪的操作,否则在默认的Spring引导应用程序中,这两个示例将执行完全相同的操作。

环境公开所有属性,您通常不希望这样。
此外,它还公开了有关配置文件的信息(区分哪些已激活,哪些已全部激活),而这些信息在这里您并不关心

属性占位符
${…}
应始终倾向于注入
环境
实例,但出于如下所述的合理原因(重点是我的):

然而,在大多数情况下,应用程序级bean不需要 直接与环境交互,但可能需要 ${…}属性值被属性占位符替换configurer 例如PropertySourcesPlaceholderConfigurer,它本身是 默认情况下,当 使用

不是直接问你的问题,但构造函数注入应该比鼓励不透明和有缺陷设计的现场注入更受欢迎:

public class MyService {   

    private final String apiPort;

    public MyService (@Value("${server.port}") String apiPort){
        this.apiPort = apiPort;
    }
}

环境公开所有属性,您通常不希望这样。
此外,它还公开了有关配置文件的信息(区分哪些已激活,哪些已全部激活),而这些信息在这里您并不关心

属性占位符
${…}
应始终倾向于注入
环境
实例,但出于如下所述的合理原因(重点是我的):

然而,在大多数情况下,应用程序级bean不需要 直接与环境交互,但可能需要 ${…}属性值被属性占位符替换configurer 例如PropertySourcesPlaceholderConfigurer,它本身是 默认情况下,当 使用

不是直接问你的问题,但构造函数注入应该比鼓励不透明和有缺陷设计的现场注入更受欢迎:

public class MyService {   

    private final String apiPort;

    public MyService (@Value("${server.port}") String apiPort){
        this.apiPort = apiPort;
    }
}

此代码可能会失败,因为Spring Boot不知道如何将
字符串
转换为
JenkinsServer
谢谢@larsgrefer,我修复了代码。此代码可能会失败,因为Spring Boot不知道如何将
字符串
转换为
JenkinsServer
谢谢@larsgrefer,我修复了代码。