我是Weld的新手,并且一直试图了解它的概念。我对Spring有一点经验,对Guice没有任何帮助,所以我几乎是DI框架的新手。
这是一个介绍CDI的教程,但是在Web应用程序的上下文中。我很想知道它在Java SE中是如何工作的。我创建了以下类,但不知道如何在Java SE应用程序中使用DefaultItemDao类(或任何其他替代方法)测试ItemProcessor的execute方法。
以下是课程:
public class Item {
private int value;
private int limit;
public Item(int v, int l) {
value = v;
limit = l;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public String toString() {
return "Item [value=" + value + ", limit=" + limit + "]";
}
}
import java.util.List;
public interface ItemDao {
List<Item> fetchItems();
}
import java.util.ArrayList;
import java.util.List;
public class DefaultItemDao implements ItemDao {
@Override
public List<Item> fetchItems() {
List<Item> results = new ArrayList<Item>(){{
add(new Item(1,2));
add(new Item(2,3));
}};
return results;
}
}
import java.util.List;
import javax.inject.Inject;
public class ItemProcessor {
@Inject
private ItemDao itemDao;
public void execute() {
List<Item> items = itemDao.fetchItems();
for (Item item : items) {
System.out.println("Found item: "+item);
}
}
}
我不知道如何为ItemProcessor类编写测试客户端。有人可以帮我理解如何用CDI写一个吗?
谢谢Kumar
答案 0 :(得分:1)
首先应该使用Google搜索
1-来自Jboss blog
2-来自Jboss code base
答案 1 :(得分:0)
我使用JavaSE注入Validator也有同样的问题。最后我设法解决了这个问题。希望它可以帮助别人!
我使用的依赖关系:
<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>
主要方法:
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);
}
}
我还在resources / META-INF目录中创建了beans.xml:
<?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>