簡體   English   中英

如何在WebAppConfig中使用@Bean和@AutoWire將屬性文件讀取到映射中?

[英]How to read a property files into a map with @Bean and @AutoWire in WebAppConfig?

我是Spring MVC的新手,我想為您提供有關如何使用Map以及@Bean和@AutoWire讀取WebAppConfig.java中的屬性文件的幫助。 屬性文件中的常量用作不同文件(如枚舉)中的公用字符串。

myproperty.properties

user.first_name = Jane
user.age = 23

WebAppConfig.java

@Configuration
@ComponentScan( {"com.nokia.care.triggerengine", "com.nokia.care.gui.commons"} )
@EnableWebMvc
@EnableTransactionManagement
@PropertySource( "classpath:application.properties" )
public class WebAppConfig
extends WebMvcConfigurerAdapter
{
...

此外,webappconfig.java已經具有一個現有的@propertsource。

謝謝您的幫助。

使用spring-boot,您可以創建一個單獨的配置組件,然后對其進行自動布線。

@Component
@ConfigurationProperties(prefix = "user")
public class UserConfig {  
    private String userFirstName;
    private String userAge;
    //getters and setters
}

public class WebAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   private UserConfig userConfig;
   ...
}

沒有spring-boot,您應該找到使用@ConfigurationProperties所需的依賴項

使用此@Value訪問bean和存儲庫類中的值

@Value("${user.first_name}")
private String userFirstName;

@Value("${user.age}")
private String userAge;

一種好的方法是讀取AppConfig類中的所有配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration

@PropertySource("classpath:myproperty.properties")
public class AppConfig {
    @Autowired
    private  Environment env;
    public  Environment getEnv(){
        return env;
    }

}

這樣,env變量將具有myproperty.properties中所有屬性的鍵值對的映射。 現在,您可以將AppConfig類插入任何您喜歡的類中。 喜歡

public class A{
.
.
@Autowired
    private AppConfig appConfig;
.
.

private void method1(){
  int age= appConfig.getEnv().getProperty("user.age");
}

這樣,您可以在一個地方分離屬性讀取邏輯,並使代碼更具模塊化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM