How to return custom Key value pair from spring-cloud-config-server? - spring-cloud-config

I am using spring-cloud-config-server , I do not want Git backend or file system based backend . I want custom Key value pair to be returned.

I found solution of this .
1) on the application.properties set spring.profiles.active=native
2) Create CustomEnvironmentRepository -- Refer code on #A
3) Register CustomEnvironmentRepository Bean -- Refer code on #B
#A -
import java.util.HashMap;
import java.util.Map;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.core.Ordered;
public class CustomEnvironmentRepository implements
EnvironmentRepository, Ordered
{
#Override
public Environment findOne(String application, String profile, String label)
{
Environment environment = new Environment(application, profile);
final Map<String, String> properties = new HashMap<>();
properties.put("mycustomPropertyKey", "myValue");
environment.add(new PropertySource("mapPropertySource", properties));
return environment;
}
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
#B
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.context.annotation.Bean;
#EnableConfigServer
#SpringBootApplication
public class MyCloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(MyCloudConfigApplication.class, args);
}
#Bean
public EnvironmentRepository environmentRepository() {
return new CustomEnvironmentRepository();
}
}
Test by invoking - http://localhost:9092/my-cloud-config.properties
You will see
mycustomPropertyKey: myValue
My Original Goal is to set some properties from Azure Key Vault , I guess integrating AzureKey Vault in CustomEnvironmentRepository , I should be able to achieve this
Application Properties File will look like
server.port=<YOUR_PORT>
spring.profiles.active=native
azure.keyvault.uri=<YOUR_AZURE_URI_CAN_BE_FOUND_IN_AZURE_PORTAL>
azure.keyvault.client-id=<YOUR_AZURE_CLIENT_ID_CAN_BE_FOUND_IN_AZURE_PORTAL>
azure.keyvault.client-key=<YOUR_AZURE_CLIENT_KEY_CAN_BE_FOUND_IN_AZURE_PORTAL>
IN POM Use these Dependencies
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-keyvault-secrets-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

Related

Cannot create ExtentReport for Selenium 3.5.1

I have tried with almost all jar files with extentreport from 2.41.2 to
3.13.0 but whenever I try to write the command: extent.loadConfig(new
File(System.getProperty("user.dir")+"//ReportsConfig.xml")); it throws error on multiple lines but for instance i have put up one example
showing as "The method loadConfig(File) is undefined for the type
ExtentReports".
My code for ExtentReport Class is `enter code here`:
package TestNG_package;
import java.io.File;
import java.util.Date;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.AbstractReporter;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentManager
{
private static ExtentReports extent;
public static String screenshotFolderPath;
static ExtentHtmlReporter htmlReporter;
public static ExtentReports getInstance()
{
if (extent == null)
{
extent = new
ExtentReport("E:\\Selenium\\Workspace\\New_Test\\test-output\\report.html");
extent.loadConfig(new
File(System.getProperty("user.dir")+"//ReportsConfig.xml"));
extent.addSystemInfo("Selenium ver" ,
"3.5.1").addSystemInfo("Environ" , "PROD");
}
return extent;
}
}
My next part of code is to invoke ExtentReport in other class called
loginTest
public class LoginTest()
{
#Test
public void doLogin()
{
ExtentReport rep = ExtentManager.getInstance();
ExtentTest Test = rep.startTest("UATRMS start");
Test.log(LogStatus.Info,"Starting UATRMS Test");
rep.endTest(test);
rep.flush();
}
}
The correct method is
reporter.loadXMLConfig("extent-config.xml");
The method you are using is for instances where you have a properties file. See the docs for more info. This method is used by the reporter, not the core API. Reporters can be configured using these configuration items.

HSQLDB with JdbcTemplate, nothing is getting saved

For some reason after doing changes to my file based HSQL database and shutting down the java process, nothing seems to be saved in the database. I.E. i can rerun this program over and over without meeting the "table already exists" exception. What the hell is going on?!
Main class:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
import java.sql.SQLException;
public class TestApp {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DbConfig.class, TestDao.class);
JdbcTemplate template = ctx.getBean(JdbcTemplate.class);
TestDao dao = ctx.getBean(TestDao.class);
dao.testTransactionality();
}
}
Config:
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
#Configuration
public class DbConfig {
#Bean
public DataSource getDataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("org.hsqldb.jdbcDriver");
ds.setUrl("jdbc:hsqldb:file:databaseFiles/test/");
ds.setUsername("sa");
ds.setPassword("1");
return ds;
}
#Bean
JdbcTemplate getJdbcTemplate(DataSource ds){
return new JdbcTemplate(ds);
}
#Bean
PlatformTransactionManager getTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
DAO:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
#Repository
#EnableTransactionManagement
#Transactional
public class TestDao {
#Autowired
private JdbcTemplate template;
#Transactional
public void testTransactionality(){
template.execute("create table LIBRARY (LIBRARY_ID INT, LIBRARY_TITLE VARCHAR(400))");
template.execute("insert into library values (1, 'Library')");
}
}
I have tried doing something similar with plain JDBC classes as well as doing explicit commits, nothing seems to help. I am guessing it's a HSQLDB problem. Please help
Your database URL is not quite right (shouldn't end with a slash). You should also change the write delay to 0 to see the changes:
ds.setUrl("jdbc:hsqldb:file:databaseFiles/test;hsqldb.write_delay_millis=0");

force glassfish 4 to use jackson 2.3

I wrote an maven application which should run on Glassfish 4.
The Standard ApplicationConfig looks like this:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
// following code can be used to customize Jersey 2.0 JSON provider:
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
addRestResourceClasses(resources);
return resources;
}
The problem now is, that my resources which generate Json should use jackson 2.3 annotations.
But my glassfish uses some codehaus. ... packages to provide json. codehaus is the old version of jackson. I want to use the new one from fasterxml which provides the #JsonIdentityInfo annotation.
I thought that i could solve my problem by writing:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
resources.add(JacksonFeatures.class); //from the com.fasterxml.jackson.jaxrs.annotation Package
resources.add(JacksonJaxbJsonProvider.class);
resources.add(JacksonJsonProvider.class);
addRestResourceClasses(resources);
return resources;
}
But no effect. Now Glassfish uses the standard JsonProvider Moxy... which i dont want to use. Do you have any tips how i can force glassfish to use my library instead of the buildin-libraries? Or can i change the buildin library to the newer one?
And if you know how to solve this. could you please provide a little code-snippet?
EDIT 1:
After trying the first approach to solve it:
new ApplicationConfig:
#javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
//register( new GZipEncoder() );
register( JacksonFeature.class );
}
private void addMyResources() {
//a lot of resources.
}
}
JacksonFeature:
public class JacksonFeature implements Feature {
public boolean configure( final FeatureContext context ) {
String postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property( CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true );
context.register( JsonParseExceptionMapper.class );
context.register( JsonMappingExceptionMapper.class );
context.register( JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class );
return true;
}
}
pom:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.4</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
</dependency>
</dependencies>
Dependencies:
http://i.stack.imgur.com/uA4V2.png
Error:
SEVERE: Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:325)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:177)
...
or
SEVERE: Exception while loading the app
SEVERE: Undeployment failed for context /blueserver
INFO: file:/C:/bluetrail/blueserver/target/blueserver-0.0.0.1/WEB-INF/classes/_de.bluetrail_blueserver_war_0.0.0.1PU logout successful
SEVERE: Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(#Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
EDIT 2:
i will now post some classes of my project. In that classes i included all Annotations that i use.
i have like 16 entities like that:
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", scope=Address.class)
//the JsonIdentityInfo is the reason i need Jackson 2
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String postalCode;
private String city;
private String country;
private String street;
private String houseNumber;
#Embedded
private Coordinate coordinate;
//getters, setters , etc.
}
then i have a lot of DAO's like that:
import de.ibs.trail.entity.Address;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
#Stateless
public class AddressDao extends GenericDao {
public Address getAddress(long id){
return em.find(Address.class, id);
}
public List<Address> getAddresses(){
List<Address> address = em.createQuery("SELECT a FROM Address a", Address.class).getResultList();
return address;
}
}
and finally i have a lot of REssources like that:
import de.bluetrail.blueserver.dao.AddressDao;
import de.ibs.trail.entity.Address;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
#Path("dummy")
#Stateless
public class DummyResource {
#Context
private UriInfo context;
#Inject userAuth user;
#Inject addressDao AddressDao;
public DummyResource() {
}
#GET
#Produces("application/json")
public List<Address> getAddress() {
return AddressDao.getAddresses();
}
}
Thats the first part. As a second part i have a class for some Google Services. Because i want to try to use some Google GeoLocation and Routing. I put the Google-Code into a pasteBin file, because its so huge:
http://pastebin.com/u3e0dms6
there i use libraries like:
import com.fasterxml.jackson.databind.ObjectMapper;
import de.ibs.trail.entity.Address;
//some other entities
//...
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
I hope that helps. All the other classes use the same annotations.
First make sure you have the following in your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version>
</dependency>
Then make sure you DO NOT have this in any pom.xml:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.5</version>
</dependency>
Then you need to disable moxy. The easiest way to do this is to ditch your Application class and replace is with a ResourceConfig class. First lets create YOUR JacksonFeature class:
public class JacksonFeature implements Feature {
public boolean configure( final FeatureContext context ) {
String postfix = '.' + context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property( CommonProperties.MOXY_JSON_FEATURE_DISABLE + postfix, true );
context.register( JsonParseExceptionMapper.class );
context.register( JsonMappingExceptionMapper.class );
context.register( JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class );
return true;
}
}
Two interesting things here, first I disabled moxy and second I made sure to add the JacksonException mappers. This way you will get better errors than internal server error if there is a parsing or generation exception. Okay, last step it so rewrite your Application as a ResourceConfig class:
#javax.ws.rs.ApplicationPath("resources")
public class RestApplication extends ResourceConfig {
public RestApplication() {
register( new GZipEncoder() );
register( JacksonFeature.class );
}
private void addMyResources() {
register( MyResource1.class );
register( MyResource2.class );
}
}
That should do it. Also, instead of registering the resources one by one like this, if you know their path you can just remove all that code and add this to the constructor of RestApplication:
package( "com.me.myrestresourcespackage" );
Hope this helps.

WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [#Default] at injection point [[field] using arquillian

I am running a basic arquillian unit test, using the Greeter example on the arquillian site. The only difference is that am doing a log.debug in the greet(PrintStream to, String name) function in Greeter.java. Am using slf4j for logging.
Greeter.java
package org.arquillian.example;
import java.io.PrintStream;
import javax.inject.Inject;
import org.slf4j.Logger;
public class Greeter {
#Inject
private Logger log;
public void greet(PrintStream to, String name) {
log.debug("Greeter Testing");
to.println(createGreeting(name));
}
public String createGreeting(String name) {
return "Hello, " + name + "!";
}
}
GreeterTest.java
package org.arquillian.example;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(Arquillian.class)
public class GreeterTest {
#Inject
Greeter greeter;
#Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClass(Greeter.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
#Test
public void should_create_greeting() {
Assert.assertEquals("Hello, Earthling!",
greeter.createGreeting("Earthling"));
greeter.greet(System.out, "Earthling");
}
}
Am getting WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [#Default] at injection point [[field] #Inject private org.arquillian.example.Greeter.log] error when running the test. Can someone please help on this?
This is a CDI issue. You don't have a producer for your Logger in the first place.
Secondly, any such producer should be added to the ShrinkWrap deployment.
A producer for the Logger is usually written as such:
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SLF4JProducer {
#Produces
public Logger producer(InjectionPoint ip){
return LoggerFactory.getLogger(
ip.getMember().getDeclaringClass().getName());
}
}
This producer receives an injection point and proceeds to return a SLF4J Logger instance. The instance has the same name as the class containing the injection point.
also change in bean.xml bean-discovery-mode to all
bean-discovery-mode="all"
Instead of injecting Logger, it worked just fine for me when I used LoggerFactory.
private Logger log = LoggerFactory.getLogger(Greeter.class);
In my case I must provide the injections programmatically
Import:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Initialization
private Logger logger;
#Inject
public LoggingInterceptor() {
logger = LoggerFactory.getLogger(LoggingInterceptor.class);
}

JBoss AS 7 application specific properties file

I have several independent Java EE modules (WAR web applications, and JAR EJB modules) which I deploy on JBoss 7.1.1 AS.
I want to:
Centralize configuration of these modules in one *.properties file.
Make this file available in classpath.
Keep the installation/configuration of this file as simple as possible. Ideally would be just to put it in some JBoss folder like: ${JBOSS_HOME}/standalone/configuration.
Make changes to this file available without restarting the application server.
Is this possible?
I already found this link: How to put an external file in the classpath, which explains that preferable way to do this is to make static JBoss module. But, I have to make dependency to this static module in every application module that I deploy, which is a kind of coupling I'm trying to avoid.
Maybe a simple solution is to read the file from a singleton or static class.
private static final String CONFIG_DIR_PROPERTY = "jboss.server.config.dir";
private static final String PROPERTIES_FILE = "application-xxx.properties";
private static final Properties PROPERTIES = new Properties();
static {
String path = System.getProperty(CONFIG_DIR_PROPERTY) + File.separator + PROPERTIES_FILE;
try {
PROPERTIES.load(new FileInputStream(path));
} catch (MalformedURLException e) {
//TODO
} catch (IOException e) {
//TODO
}
}
Here is a full example using just CDI, taken from this site.
This configuration will also work for JBoss AS7.
Create and populate a properties file inside the WildFly configuration folder
$ echo 'docs.dir=/var/documents' >> .standalone/configuration/application.properties
Add a system property to the WildFly configuration file.
$ ./bin/jboss-cli.sh --connect
[standalone#localhost:9990 /] /system-property=application.properties:add(value=${jboss.server.config.dir}/application.properties)
This will add the following to your server configuration file (standalone.xml or domain.xml):
<system-properties>
<property name="application.properties" value="${jboss.server.config.dir}/application.properties"/>
</system-properties>
Create the singleton session bean that loads and stores the application wide properties
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);
}
}
Create the CDI Qualifier. We will use this annotation on the Java variables we wish to inject into.
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();
}
Create the producer method; this generates the object to be injected
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
public class ApplicationPropertyProducer {
#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);
}
}
Lastly inject the property into one of your CDI beans
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;
}
}