如何从Application.properties中检索值?

时间:2016-11-02 20:26:44

标签: spring-boot

属性代码段。

# Email (MailProperties)
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
spring.mail.host= # SMTP server host. For instance `smtp.example.com`
spring.mail.jndi-name= # Session JNDI name. When set, takes precedence to others mail settings.
spring.mail.password= # Login password of the SMTP server.
spring.mail.port= # SMTP server port.
spring.mail.properties.*= # Additional JavaMail session properties.
spring.mail.protocol=smtp # Protocol used by the SMTP server.
spring.mail.test-connection=false # Test that the mail server is available on startup.
spring.mail.username= # Login user of the SMTP server.
some.prop = testingTesting

如何在java类中检索springmail.protocol或多个属性?

尝试

    @Component
public class MyBean {

    private final String prop;

    @Autowired
    public MyBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        System.out.println("================== " + prop + "================== ");
    }
}

我目前正在使用此方法从app.properties文件中打印出我的属性。我想注释的不只是一个值。

@value "{some.prop, second.prop, 3rd.prop}") String prop, propOne, Prop2

可以调用多个值吗?在我实例化此类中的属性之后,如何在另一个类中使用这些属性?

1 个答案:

答案 0 :(得分:2)

您可以轻松注释多个参数

@Autowire

您也可以org.springframework.core.env.Environment getProperty的实例(作为方法参数或实例字段)并调用ord()方法来获取属性值。

将单个属性注入@Value通常会更好,因为它不会将您的业务逻辑绑定到Spring API。

在Spring Boot中,您还可以在类上使用注释@ConfigurationProperties(prefix =“connection”)来注入多个属性。有关详细信息,请参阅http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

相关问题