Skip to content

UsingCDIWithJavaScript

Sebastian Hoß edited this page Oct 3, 2013 · 7 revisions

To use CDI together with JavaScript, declare the following dependencies

<dependencies>
  <dependency>
    <groupId>com.github.sebhoss.contract</groupId>
    <artifactId>contract-cdi</artifactId>
    <version>${contracts-version}</version>
  </dependency>
  <dependency>
    <groupId>com.github.sebhoss.contract</groupId>
    <artifactId>contract-scriptengine</artifactId>
    <version>${contracts-version}</version>
  </dependency>
</dependencies>

then expose the provided @Script ContractContextFactory as the @Default ContractContextFactory. Additionally provide a JavaScript-based ScriptEngine as shown below:

import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.github.sebhoss.contract.annotation.Script;
import com.github.sebhoss.contract.verifier.ContractContextFactory;

class ContractContextFactoryProducer {

    @Produces
    @Default
    ScriptEngine javaScriptEngine() {
        return new ScriptEngineManager().getEngineByName("JavaScript");
    }

    @Produces
    @Default
    ContractContextFactory contextFactory(@Script ContractContextFactory scriptFactory) {
        return scriptFactory;
    }

}

Annotate your business methods as usual using JavaScript. Consult the example project for more details.