Java 如何使用Spring创建配置类并在整个代码中共享数据?

Java 如何使用Spring创建配置类并在整个代码中共享数据?,java,spring,spring-boot,Java,Spring,Spring Boot,我需要创建类似共享类的东西,我可以用以下方式使用: Shared.getProperty(key); 我尝试使用Environment对象,但它总是空的。应在何处指定,如何指定? 我使用.xml进行bean配置。 我还有application.properties,我想从中检索数据 最好的方法是在application.properties文件中定义属性,然后您可以使用@Value annotation访问这些属性。我这样做的方法是在application.properties中定义值,然后创

我需要创建类似共享类的东西,我可以用以下方式使用:

Shared.getProperty(key);
我尝试使用Environment对象,但它总是空的。应在何处指定,如何指定? 我使用.xml进行bean配置。
我还有application.properties,我想从中检索数据

最好的方法是在application.properties文件中定义属性,然后您可以使用@Value annotation访问这些属性。

我这样做的方法是在
application.properties
中定义值,然后创建配置类,例如:

// Shared.java
@Component
@ConfigurationProperties("prefix.for.application.properties")
public class Shared {
    private String str;

    // getters, setters
}

// application.properties
prefix.for.application.properties.str=STR

// other code
@Autovired
private Shared shared;

shared.getStr(); 
application.properties中定义常量

app.email_subject =My app Registration
app.email_from =Some person
带注释的类

@Configuration    
@ConfigurationProperties(prefix = "app")
public class GlobalProperties {

    @Value("email_subject")
    private String emailSubject;
    @Value("email_from")
    private String emailFrom;

    // getters and setters
}
您可以在任何地方使用此类,如下所示:

@Service
public class SomeService {
    @Autowired
    private GlobalProperties globalProperties;

    public someMethod() {
        System.out.println(globalProperties.getEmailFrom());
    }
}

您想要的是完全共享的.getProperty(key),而不是共享的.getKey()?这没关系。只是为了有一个共享对象,所以我可以在代码中的任何地方使用它。但我当然希望通过键检索值。抱歉,我不使用XML配置。您能提供有关错误消息的更多详细信息吗?仅在调用globalProperties的位置出现NullPointerException。getEmailFrom()配置如何?我的SomeService是一个bean,它也在我的XML文件中声明。我不做xml配置,我的工作示例使用注释。如果它是用XML声明的,您可能需要更新它,以便spring知道它将使用GlobalProperty,但我不确定,我很久没有使用XML了。