【问题标题】:Spring - Set property value using annotations without using properties fileSpring - 使用注释设置属性值而不使用属性文件
【发布时间】:2018-07-20 20:44:56
【问题描述】:

我有一个 bean 类,例如

class Sample {
    private String message;
    public void setMessage(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

我想设置这个属性的值。

在 Xml 配置中,我可以做到

<bean id = "sample" class = "Sample"
    <property name = "message" value = "Hello there!"/>
</bean>

如何实现相同的目的,即使用 Java Annotation 设置属性的值?现在我已经读到我们可以使用一些属性文件来使用@Value 注释,但是如果不使用属性文件就不能做到这一点,就像我通过 xml 文件做的那样?或者使用属性文件是必要的

我可以通过在 setter 方法上方包含 @Value("Hello there!") 来做到这一点。但我能感觉到这不是一个好主意。如何使用 Java Annotations 为不同的实例设置属性值?

谢谢。

【问题讨论】:

    标签: java spring spring-annotations


    【解决方案1】:

    插入到@Value 中的值可以来自属性文件以外的地方,例如它也可以使用系统属性。

    使用指南here 作为起点应该可以帮助您更好地理解。

    作为一个基本且几乎无用的用法示例,我们只能注入“字符串 值”从注释到字段:

    @Value("string value")
    private String stringValue;
    

    使用@PropertySource 注解可以让我们使用值 来自带有 @Value 注释的属性文件。在下面的 例如,我们将“从文件中获取的值”分配给该字段:

    @Value("${value.from.file}")
    private String valueFromFile;
    

    我们还可以使用相同的语法从系统属性中设置值。 假设我们已经定义了一个名为 systemValue 的系统属性 并查看以下示例:

    @Value("${systemValue}")
    private String systemValue;
    

    可以为可能没有的属性提供默认值 定义。在此示例中,将注入值“一些默认值”:

    @Value("${unknown.param:some default}")
    private String someDefault;
    

    【讨论】:

      【解决方案2】:

      您有几个选择,具体取决于您的要求。在这两个示例中,您都可以在 setter 而不是字段上设置注释。

      自定义属性来源

      这使您可以继续使用@Value,并更好地控制属性的提供方式。有大量的PropertySource 实现,但您始终可以创建自己的。

      参考资料:

      例子:

      @Configuration
      class MyConfiguration {
        @Bean
        PropertySource myPropertySource(ConfigurableEnvironment env) {
          MapPropertySource source = new MapPropertySource("myPropertySource", singletonMap("myPropertyValue", "example"));
          env.getPropertySources().addFirst(source);
          return source;
        }
      }
      
      class Sample {
        @Value("${myPropertyValue}")
        private String message;
      
        public String getMessage() {
          return message;
        }
      }
      

      菜豆

      将 bean 定义为 String 并使用其限定符自动连接它。

      例子:

      @Configuration
      class MyConfiguration {
        @Bean
        String myPropertyValue() {
          String value;
          // do something to get the value
          return value;
        }
      }
      
      class Sample {
        @Autowired
        @Qualifier("myPropertyValue")
        private String message;
      
        public String getMessage() {
          return message;
        }
      }
      

      【讨论】:

      • 嗨,实际上我想使用基于注释的配置来设置它。我假设配置和 Bean 注释属于基于 Java 的配置?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多