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

我需要创建类似 Shared 类的东西,我可以通过以下方式使用它:

Shared.getProperty(key);

我尝试使用 Environment 对象,但它始终为空。应该在哪里指定以及如何指定?我将 .xml 用于我的 bean 配置。我也有 application.properties,我想从中检索数据。


MMMHUHU
浏览 115回答 3
3回答

Smart猫小萌

// Shared.java@Component@ConfigurationProperties("prefix.for.application.properties")public class Shared {    private String str;    // getters, setters}// application.propertiesprefix.for.application.properties.str=STR// other code@Autoviredprivate Shared shared;shared.getStr(); 

蝴蝶刀刀

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

元芳怎么了

我这样做的方法是使用定义值application.properties然后创建一个配置类,例如:定义常量application.propertiesapp.email_subject =My app Registrationapp.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}你可以在任何你想要的地方使用这个类,如下所示:@Servicepublic class SomeService {    @Autowired    private GlobalProperties globalProperties;    public someMethod() {        System.out.println(globalProperties.getEmailFrom());    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java