Spring 技巧 - @Value 复用
平时我们想将 Spring Boot 配置文件中的值注入到变量中,我们可以使用 @Value 注解,如:
平时我们想将 Spring Boot 配置文件中的值注入到变量中,我们可以使用 @Value 注解,如:
server:
port: 8080@Value("${server.port}")
private Integer port;但是,如果代码中有多个地方想使用的话,就需要在多个地方都使用 @Value 注解,这样就会显得很麻烦,而且如果配置文件中的值发生了变化,那么我们就需要在多个地方都修改,容易出错。
为了解决这个问题,我们可以抽取一个自定义注解,如:
import org.springframework.beans.factory.annotation.Value;
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${server.port}")
public @interface ServerPort {
}然后在需要使用的地方使用该注解,如:
import org.springframework.stereotype.Component;
@Component
public class TestService {
@ServerPort
private Integer port;
public void test() {
System.out.println(port);
}
}这样使用自定义注解和 @Value 注解的效果是一样的,但是可以减少代码量,而且如果配置文件中的值发生了变化,我们只需要修改自定义注解即可。
不过这只适用于使用 @Value 注解的场景,更推荐的做法是将配置文件中的值注入到一个对象中,然后在需要使用的地方注入该对象,如:
server:
port: 8080
address: 127.0.0.1import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
private Integer port;
private String address;
// getter and setter
}