Weld and Java SE

别说谁变了你拦得住时间么 提交于 2019-12-06 06:07:49

Should have googled it first.
1- From Jboss blog
2- From Jboss code base

I had same question with injection Validator using JavaSE. Finally I managed to solve it. Hope it helps someone!

Dependencies i used:

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.0.Alpha2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-cdi</artifactId>
            <version>6.0.0.Alpha2</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.weld.se</groupId>
            <artifactId>weld-se</artifactId>
            <version>2.4.3.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
        </dependency>

Main method:

    Weld weld = new Weld().interceptors(Validator.class);
    WeldContainer container = weld.initialize();
    PurchaseOrderService service = 
    container.select(ru.code.service.PurchaseOrderService.class).get();
    Customer customer = new Customer(.....);
    service.createCustomer(customer);
    weld.shutdown();

PurchaseOrderService.java

@Inject
private Validator validator;
private Set<ConstraintViolation<Customer>> violations;   

public PurchaseOrderService() {
}

public void createCustomer(Customer customer) {
    violations = validator.validate(customer);
    if (violations.size() > 0) {
        throw new ConstraintViolationException(violations);
    }
}

And also i created beans.xml in resources/META-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="all">
</beans>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!