简体   繁体   English

如何从该配置文件获取属性到另一个Java类?

[英]How can I get the properties from this config file to another java class?

I was able to extract the properties from an application.properties file. 我能够从application.properties文件中提取属性。 But I was unable to use it in another class. 但是我无法在其他课程中使用它。

ConfigFile 配置文件

package com.springweb.springApplication.config;    
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;    

@Component
public class AppConfig {

private final String App;    
private final String servers;    

@Autowired
public AppConfig(@Value("${Application}") String App,
                @Value("${APP_SERVERS}") String servers) {
    this.App = App;
    this.servers = servers;

    System.out.println("================ " + servers + "================ ");
}    

public String getApp() {
    return App;
}

public String getServers() {
    return servers;
}

}

Class code SNippet 类代码SNippet

public class MyFirstClass{

private String RED = "RED";
private String GREEN = "GREEN";
private String YELLOW = "YELLOW";   


public List<ModelSet> findall() {


    Properties prop = new Properties();
    InputStream input = null;

            try {
                input = new
                FileInputStream("C:/Users/Jackie/workspace/springApplication/lib/myConfig.properties");
                prop.load(input);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                           


        String servers = prop.getProperty("APP_SERVERS");
        String Application = prop.getProperty("Application");
}

I want to replace inputSteam and use the properties file internally. 我想替换inputSteam并在内部使用属性文件。 Instead of having stream to find the file. 而不是用流来查找文件。 I want to get those variables from the config file. 我想从配置文件中获取这些变量。 I tried looking at http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html but I could not find how to call the variables into another class. 我尝试查看http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html,但找不到如何将变量调用到另一个类中。 I only have a slightest clue on how to apporach this. 我对如何解决这个问题只有丝毫线索。 Right now I believe I have to do something like .getproperty or env properties. 现在,我相信我必须执行.getproperty或env属性之类的操作。

Inject AppConfig into the MyFirstClass class. AppConfig注入MyFirstClass类。

Edit: I may not understand what you are asking. 编辑:我可能不明白你在问什么。

Here is option 1 of what I think you want: Summarized as "I injected stuff into AppConfig and want to reference that injected stuff in MyFirstClas". 这是我想要的选项1:概括为“我向AppConfig中注入了东西,并希望在MyFirstClas中引用该注入的东西”。

  1. Keep the configuration for the AppConfig class. 保留AppConfig类的配置。
  2. Add an @Inject (or @Autowired) member of type AppConfig to the MyFirstClass class. 将类型为AppConfig的@Inject(或@Autowired)成员添加到MyFirstClass类。
  3. Call the AppConfig getters to retrieve the config values. 调用AppConfig获取器以获取配置值。

Here is option 2 of what I think you want: Summarized as "I injected properties in some class and want to inject more properties in some other class" 这是我想要的选项2:总结为“我在某个类中注入了属性,并希望在其他类中注入了更多属性”

  1. Create a PropertyPlaceholderConfigurer in your Spring configuration (search for PropertyPlaceholderConfigurer in the Spring Reference or on google) 在您的Spring配置中创建一个PropertyPlaceholderConfigurer (在Spring参考或Google中搜索PropertyPlaceholderConfigurer)
  2. Inject the properties into your "some other class" using configuration similar to this: <property name="memberNameInYourClass" value="${propertyName.from.properties.file}"/> 使用类似于以下的配置将属性注入“其他类”中: <property name="memberNameInYourClass" value="${propertyName.from.properties.file}"/>

I was able to extract the properties from an application.properties file. 我能够从application.properties文件中提取属性。 But I was unable to use it in another class. 但是我无法在其他课程中使用它。

You was not able to get properties in MyFirstClass with @Value because MyFirstClass is not a Spring component so @Value was ignored. 您无法使用@Value获取MyFirstClass中的属性,因为MyFirstClass不是Spring组件,因此@Value被忽略。

Annotate MyFirstClass as Spring Component and Inject properties with @Value should solve the issue 将MyFirstClass注释为Spring Component并使用@Value注入属性应解决此问题

Update : Injection is done after the constructor is called 更新 :在构造函数被调用后完成注入

@Component
public class MyFirstClass{

    private String app;

    private String servers;

    @Autowired
    public MyFirstClass(@Value("${Application}") String App,
            @Value("${APP_SERVERS}") String servers) {
        this.App = App;
        this.servers = servers;

        System.out.println("================ " + servers + "================ ");
    } 

    private String RED = "RED";
    private String GREEN = "GREEN";
    private String YELLOW = "YELLOW";   


    public List<ModelSet> findall() {
        // process findall Spring will resolve properties for you!
    }
}

You can get the properties by injecting Environment to the class. 您可以通过将Environment注入到类中来获取属性。

public class MyFirstClass{

@Autowired
private Environment env;

private String RED = "RED";
private String GREEN = "GREEN";
private String YELLOW = "YELLOW";   


public List<ModelSet> findall() {


Properties prop = new Properties();
InputStream input = null;

        try {
            input = new
            FileInputStream(env.getProperty("a.b.c.path"));
            prop.load(input);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }                           


    String servers = prop.getProperty("APP_SERVERS");
    String Application = prop.getProperty("Application");
}

in your application.properties file, define the path like 在application.properties文件中,定义路径,例如

a.b.c.path = /home/jackie/asd

Class

@Component
public class MyFirstClass{


@Value("${Application}")
private String Application;
@Value("${APP_SERVERS}")
private String servers; 


private String RED = "RED";
private String GREEN = "GREEN";
private String YELLOW = "YELLOW";   


@PostConstruct
public List<ModelSet> findall() {

//normal code that called the properties variables will be read automatically.
System.out.println(Application + "this is application from properties");
}

Output 输出量

Hellosir this is application from properties

Application.properties Application.properties

Application = Hellosir
Servers = server1,server2,server3

This worked for me and what I needed. 这对我和我需要的东西都有效。 I added @Component above the class, and added @PostConstruct below. 我在类上方添加了@Component,并在下面添加了@PostConstruct。 Now it will print the properties value. 现在它将打印属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM