DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Implement Hibernate Second-Level Cache With NCache

Trending

  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Caching 101: Theory, Algorithms, Tools, and Best Practices
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How to @Inject Property File Properties With CDI

How to @Inject Property File Properties With CDI

Learn how to @inject Property files for your Java app with CDI in this neat tutorial, with annotations, producers, and more!

By 
Ivo Woltring user avatar
Ivo Woltring
·
Mar. 15, 16 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
45.1K Views

Join the DZone community and get the full member experience.

Join For Free

Problem

You use CDI for your Java application and want to use a Property file for some needed configuration, but don't know how to do this...

Solution

Create @Producer(s) and an annotation to direct it.

Annotation

package nl.ivonet.config;

import javax.enterprise.util.Nonbinding;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Represents an property key to be injected
 */
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Property {
    @Nonbinding String value() default "";
    @Nonbinding boolean required() default true;
}

Producer

The examples provided here enable parsing of Strings, Booleans and Integers but you can, of course, add producers as needed. Note that the getKey method first looks if the @Property annotation has a value and if so it will take that as the key for the property file, but if you don't provide a value it will take the annotated field name as the key.

package nl.ivonet.config;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyProducer {
    private Properties properties;

    @Property
    @Produces
    public String produceString(final InjectionPoint ip) {
        return this.properties.getProperty(getKey(ip));
    }

    @Property
    @Produces
    public int produceInt(final InjectionPoint ip) {
        return Integer.valueOf(this.properties.getProperty(getKey(ip)));
    }

    @Property
    @Produces
    public boolean produceBoolean(final InjectionPoint ip) {
        return Boolean.valueOf(this.properties.getProperty(getKey(ip)));
    }

    private String getKey(final InjectionPoint ip) {
        return (ip.getAnnotated()
                  .isAnnotationPresent(Property.class) && 
                !ip.getAnnotated()
                   .getAnnotation(Property.class)
                    value().isEmpty()) ? ip.getAnnotated()
                                           .getAnnotation(Property.class)
                                           .value() 
                                       : ip.getMember()
                                           .getName();
    }

    @PostConstruct
    public void init() {
        this.properties = new Properties();
        final InputStream stream = PropertyProducer.class
                                      .getResourceAsStream("/application.properties");
        if (stream == null) {
            throw new RuntimeException("No properties!!!");
        }
        try {
            this.properties.load(stream);
        } catch (final IOException e) {
            throw new RuntimeException("Configuration could not be loaded!");
        }
    }
}

Usage

  @Inject
  @Property
  private String rootFolder;

or

  @Inject
  @Property("root.folder.key.here")
  private String rootFolder;

application.properties

rootFolder=/helloWorldFolder
root.folder.key.here=/another/folder/name

Extra Consideration

Note that when using this method for injecting Strings and stuff it might get difficult to write Unit tests as Mocking frameworks cannot Mock final classes (e.g. String). If you get to this problem you might want to look at this article.

Have fun,

Ivo.

CDI Property (programming)

Published at DZone with permission of Ivo Woltring. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Implement Hibernate Second-Level Cache With NCache

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!