Reputation: 1225
What is the way one inject property value from property placeholder into CDI bean?
In Spring one write:
@org.springframework.beans.factory.annotation.Value("${webservice.user}")
private String webserviceUser;
what sets the webserviceUser
field to property webservice.user
from property file/property placeholder.
How to do that with CDI? I've tried to find some answer, but I couldn't find any equivalent. However, people write, you can use CDI as Spring substitute on application servers, and that use case is very basic, so surely there must be an easy way, unfortunately I've failed to find it.
Upvotes: 6
Views: 3265
Reputation: 4970
CDI is a specification about Dependecy Injection and Context so it doesn't have such configuration things out of the box. But it also provides a very powerful extension mechanism that allows third party projects to add new portable features (i.e that works with all CDI implementation and that are not tied to a server). The most important project providing CDI extensions is Apache Deltaspike and good news, it provides what you need.
So you need to add deltaspike-core in your project. If you use Maven, you need to add this dependencies to your pom.xml
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-api</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-impl</artifactId>
<version>0.4</version>
</dependency>
After that if you don't care about your properties filename, just add META-INF/apache-deltaspike.properties
to your project and put your properties in it. If you need more than one file or want to choose the name you'll have to implement PropertyFileConfig
interface for each file like this :
public class MyCustomPropertyFileConfig implements PropertyFileConfig
{
@Override
public String getPropertyFileName()
{
return "myconfig.properties";
}
}
After that you'll be able to inject values like this
@ApplicationScoped
public class SomeRandomService
{
@Inject
@ConfigProperty(name = "endpoint.poll.interval")
private Integer pollInterval;
@Inject
@ConfigProperty(name = "endpoint.poll.servername")
private String pollUrl;
...
}
As you see in this example taken from Deltaspike documentation, you can inject your value in String but also in Integer, Long, Float, Boolean fields. You could provide your own type if you need something more specific. Deltaspike config documentation can be found here.
Upvotes: 6