我正在尝试在java SE中设置一个非常简单的焊接实现.
我有扩展类:
public class MyExtension implements Extension {
void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd) {
System.out.println("Starting scan...");
}
<T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> annotatedType, BeanManager beanManager) {
System.out.println("Scanning type: " + annotatedType.getAnnotatedType().getJavaClass().getName());
}
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) {
System.out.println("Finished the scanning process");
}
public void main(@Observes ContainerInitialized event) {
System.out.println("Starting application");
new Test();
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个我想要注入的简单类:
public class SimpleClass {
public void doSomething() {
System.out.println("Consider it done");
}
}
Run Code Online (Sandbox Code Playgroud)
最后我要把它注入的课程:
public class Test {
@Inject
private SimpleClass simple;
@PostConstruct
public void initialize() {
simple.doSomething();
}
@PreDestroy
public void stop() {
System.out.println("Stopping");
}
}
Run Code Online (Sandbox Code Playgroud)
结果输出是:
80 [main] INFO org.jboss.weld.Version - WELD-000900 1.1.10 (Final)
272 [main] INFO org.jboss.weld.Bootstrap - WELD-000101 Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Starting scan...
Scanning type: test.Test
Scanning type: test.SimpleClass
Scanning type: test.MyExtension
640 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
640 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled
Finished the scanning process
Starting application
Run Code Online (Sandbox Code Playgroud)
我希望在构造Test()时调用简单类,并调用应该输出预期文本的postconstruct方法.
我究竟做错了什么?
您的代码存在两个问题:
问题1:
CDI不管理使用的bean创建new.在大多数情况下,您需要@Inject a bean以使其生命周期由容器管理
问题2:
在大多数情况下,您不能将bean实例注入容器事件的观察者.这是因为事件在容器初始化时触发,即在它实际上可以开始管理对象生命周期之前.
您可以将容器初始化程序观察器直接挂接到Test类中.像这样的东西:
public class SimpleClass {
public void doSomething() {
System.out.println("Consider it done");
}
@PostConstruct
public void initialize() {
System.out.println("Starting");
}
@PreDestroy
public void stop() {
System.out.println("Stopping");
}
}
public class Test {
@Inject
private SimpleClass simple;
public void main(@Observes ContainerInitialized event) {
System.out.println("Starting application");
simple.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10102 次 |
| 最近记录: |