wildfly:从配置目录读取属性

wtlkbnrh  于 2021-06-30  发布在  Java
关注(0)|答案(7)|浏览(282)

我正在尝试从wildfly配置文件夹中的属性文件中读取特定于部署的信息。我试过这个:

@Singleton
@Startup
public class DeploymentConfiguration {

  protected Properties props;

  @PostConstruct
  public void readConfig() {

    props = new Properties();
    try {
      props.load(getClass().getClassLoader().getResourceAsStream("my.properties"));
    } catch (IOException e) {
      // ... whatever
    }
  }

但是很明显,由于配置文件夹不在类路径中,所以这不起作用。现在我找不到一个简单的方法。我最喜欢的是这样:

@InjectProperties("my.properties")
protected Properties props;

到目前为止,我在web上找到的唯一解决方案是制作自己的osgi模块,但我相信一定有更简单的方法(没有osgi的方法!)。有人能告诉我怎么做吗?

sc4hvdpw

sc4hvdpw1#

下面是一个使用cdi的完整示例,来自这个站点。
在wildfly配置文件夹中创建并填充属性文件

$ echo 'docs.dir=/var/documents' >> .standalone/configuration/application.properties

向wildfly配置文件添加系统属性。

$ ./bin/jboss-cli.sh --connect
[standalone@localhost:9990 /] /system-property=application.properties:add(value=${jboss.server.config.dir}/application.properties)

这将向服务器配置文件(standalone.xml或domain.xml)添加以下内容:

<system-properties>
    <property name="application.properties" value="${jboss.server.config.dir}/application.properties"/>
</system-properties>

创建加载和存储应用程序范围属性的单例会话bean

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;

@Singleton
public class PropertyFileResolver {

    private Logger logger = Logger.getLogger(PropertyFileResolver.class);
    private String properties = new HashMap<>();

    @PostConstruct
    private void init() throws IOException {

        //matches the property name as defined in the system-properties element in WildFly
        String propertyFile = System.getProperty("application.properties");
        File file = new File(propertyFile);
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            logger.error("Unable to load properties file", e);
        }

        HashMap hashMap = new HashMap<>(properties);
        this.properties.putAll(hashMap);
    }

    public String getProperty(String key) {
        return properties.get(key);
    }
}

创建cdi限定符。我们将在希望注入的java变量上使用这个注解。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR })
public @interface ApplicationProperty {

    // no default meaning a value is mandatory
    @Nonbinding
    String name();
}

创建生产者方法;这将生成要注入的对象

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;

public class ApplicaitonPropertyProducer {

    @Inject
    private PropertyFileResolver fileResolver;

    @Produces
    @ApplicationProperty(name = "")
    public String getPropertyAsString(InjectionPoint injectionPoint) {

        String propertyName = injectionPoint.getAnnotated().getAnnotation(ApplicationProperty.class).name();
        String value = fileResolver.getProperty(propertyName);

        if (value == null || propertyName.trim().length() == 0) {
            throw new IllegalArgumentException("No property found with name " + value);
        }
        return value;
    }

    @Produces
    @ApplicationProperty(name="")
    public Integer getPropertyAsInteger(InjectionPoint injectionPoint) {

        String value = getPropertyAsString(injectionPoint);
        return value == null ? null : Integer.valueOf(value);
    }
}

最后,将属性注入一个cdibean

import javax.ejb.Stateless;
import javax.inject.Inject;

@Stateless
public class MySimpleEJB {

    @Inject
    @ApplicationProperty(name = "docs.dir")
    private String myProperty;

    public String getProperty() {
        return myProperty;
    }
}
3phpmpom

3phpmpom2#

如果要从配置目录显式读取文件(例如。 $WILDFLY_HOME/standalone/configuration 或者 domain/configuration )有一个包含路径的系统属性。简单地做 System.getProperty("jboss.server.config.dir"); 并将您的文件名附加到该文件以获取该文件。
你不会把它当作资源来读,所以。。。

String fileName = System.getProperty("jboss.server.config.dir") + "/my.properties";
try(FileInputStream fis = new FileInputStream(fileName)) {
  properties.load(fis);
}

然后文件将为您加载。
另外,由于wildfly不再提供osgi支持,我不知道创建osgi模块会对您有什么帮助。

7ajki6be

7ajki6be3#

为了避免这种问题,问题是设置 jboss.server.config.dir 在类似的vm参数中:

-Djboss.server.config.dir="[jboss_repository]/server/[default-all-standard-standalone]/conf" –server
x8goxv8g

x8goxv8g4#

如果在standalone.xml属性中有:

<property name="my.properties" value="propertyValue"/>

你可以通过以下方式阅读:

static final String MY_PROPERTY = System.getProperty("my.properties");

或者在web.xml中指定context param,例如:

<context-param>
    <param-name>MyProperty</param-name>
    <param-value>MyPropertyValue</param-value>
</context-param>

您可以在java bean中阅读:

String myProperty= getServletContext().getInitParameter("MyProperty");
nwlls2ji

nwlls2ji5#

InputStream in = null;
File confDir = new File(System.getProperty("jboss.server.config.dir"));
File fileProp = new File(confDir, "my.properties");

try{
    //teste fileProp.exists etc.

    in = new FileInputStream(fileProp);
    Properties properties = new Properties();
    properties.load(in);

    //You should throws or handle FileNotFoundException and IOException
}finally{
    try{
        in.close();
    }catch(Exception ignored){
    }
}
gg58donl

gg58donl6#

听起来您试图解决的问题是管理不同(但可能相似)的配置文件,以便在不同的环境(即生产环境、qa环境,甚至不同的客户)中运行应用程序。如果是这样的话,看看jfighttp://jfig.sourceforge.net/ . 它将消除在类路径之外存储属性文件的需要(但仍然可以)。
我们需要的是配置文件的分层方法。90%不变的配置值可以保存在基本文件中。其他百分之十(或更少)可以保存在他们自己独特的配置文件中。在运行时,这些文件彼此层叠,以提供灵活、可管理的配置。例如,在开发环境中,myhost.config.xml与dev.config.xml和base.config.xml组合在一起形成我的唯一配置。
然后可以在版本控制中维护每个配置文件,因为它们具有唯一的名称。当基值更改时,只需要修改基文件,很容易看出版本之间的差异。另一个主要好处是,对基本配置文件的更改将在部署之前进行彻底的测试。

sqougxex

sqougxex7#

你能做的最简单的事就是跑步 standalone.sh 用一个 -P 选项引用您的属性文件(您需要一个url file:/path/to/my.properties ,或将文件放入 $WILDFLY_HOME/bin ).
然后文件中的所有属性将作为系统属性加载。
要将配置属性注入到应用程序类中,请查看deltaspike配置,它支持不同的属性源,如系统属性、环境变量、jndi条目,并对应用程序隐藏特定的源。
或者,为了避免设置系统属性(对于部署到wildfly示例的所有应用程序来说,这些属性都是全局的),您还可以为deltaspike定义一个自定义属性源,以便从任何给定位置读取属性文件,并且这些属性将是应用程序的本地属性。

相关问题