Reputation: 433
Have some business logic using CDI (@javax.inject.Inject and @javax.persistence.PersistenceUnit). Want reuse it inside desctop application.
Added beans.xml into META-INF folder. Set Java 7 as default. Wrote simple class:
public class Main {
@Inject
private static AggregatedUserQueries aggregatedUserQueries;
public static void main(String[] args) {
System.out.println(aggregatedUserQueries);
}
}
Of course it prints "null" to console. Are there any way to use CDI with desctop application?
Upvotes: 2
Views: 1623
Reputation: 1420
As mentioned @Boris Pavlović
, you can bootstrap Weld and get beans programmatically. However, it is possible to get injection working too. You need to define startup method in your desktop application which will "replace" your public static void main(String ... args)
. Consider:
public class Main {
@Inject
private Bean bean;
public void startup(@Observes ContainerInitialized event) {
this.bean.sayHello();
}
}
This startup()
method will be invoked when Weld is bootstraped. You can achieve it by executing org.jboss.weld.environment.se.StartMain
as a main class.
Upvotes: 3
Reputation: 64632
Add weld to your project
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.2.12.Final</version>
</dependency>
then somewhere in your application initialize it:
WeldContainer weld = new Weld().initialize();
and lookup a bean:
AggregatedUserQueries queries =
weld.instance().select(AggregatedUserQueries.class).get();
Upvotes: 1