标签: cdi

分层架构中的CDI.如何使用CDI注释注入服务对象?

我正在开发一些应用程序,它由三层组成:

  1. 数据库访问层(JPA + Hibernate作为提供者)
  2. 业务逻辑层
  3. 表示层(JSF 2.0)

在开始之前,我已经阅读了David Geary和Cay S. Horstmann撰写的Core JavaServer Faces(第3版)一书中的一些章节.在本书中,作者强烈建议使用@Named注释而不是@ManagedBean.好的,我以为我可以试试.

然后我通过实现一些基本功能 - 用户登录来继续构建我的应用程序.

我还读到了一些新的注释,即@Inject.我认为只在接口上注入一层到另一层是非常舒服的.但是我害怕我误解了一些东西,所以我带着问题来找你.

让我介绍一下我的代码的一些部分:

CredentialsBean.java:

@Named("userCredentials")
public class CredentialsBean {
    @Inject
    AccountService accountService;

    private String login;
    private String password;

    public String verify()
    {
        if (accountService.verifyCredentials(login, password))
            return "success";
        else
            return "failure";
    }
    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

AccountService.java:

public interface AccountService {
    public Boolean verifyCredentials(String login, String password);
}
Run Code Online (Sandbox Code Playgroud)

AccountServiceImpl.java:

public class AccountServiceImpl implements AccountService {
    @Inject
    AccountDAO …
Run Code Online (Sandbox Code Playgroud)

dependency-injection layer cdi jsf-2

5
推荐指数
1
解决办法
2261
查看次数

在EntityListener中注入SessionScoped有状态bean

我正在尝试在GlassFish 3上的Java EE JPA应用程序中实现某种审计.

@EntityListeners在我的@MappedSuperclass实体上添加了一个注释,监听器在其方法上有注释@PrePersist@PreUpdate注释,这些注释在运行时被愉快地调用.

在这些方法中,我试图用(@Inject)一@Named,@Stateful,@SessionScoped豆(UserSession为了获得当前用户的ID).监听器类根本没有注释.

问题是我无法UserSession注入豆子; 我总是最终得到一个null价值.到目前为止,我尝试了总是注入空值的plain .我@Inject UserSession us;也尝试过UserSession us = (UserSession) ctx.lookup("java:global/application/module/UserSession");总是返回一个新对象(我验证了构造函数调用,加上对象为).

我很确定我错过了一些关于CDI非常重要但我无法弄清楚是什么.有人可以指出我正确的方向吗?

java ejb glassfish javabeans cdi

5
推荐指数
1
解决办法
3195
查看次数

您如何找出异常导致CDI事务回滚的原因?

我们正在使用CDI与CMT(容器管理事务)连接到Web应用程序中的数据库,并标记从前端调用的需要事务的方法:

@Transactional(value=TxType.REQUIRES_NEW)
Run Code Online (Sandbox Code Playgroud)

这将创建一个新的CDI事务,但是现在如果执行此代码块或从此方法调用的任何其他代码块发生异常,它将抛出错误消息:

javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
Run Code Online (Sandbox Code Playgroud)

无论如何让CDI重新抛出嵌套错误,以便您可以轻松调试回滚的真正原因是什么?

(在Java-EE7上运行,Glassfish 4.0,JSF 2.2.2)

java transactions java-ee cdi

5
推荐指数
1
解决办法
3783
查看次数

从EJB调用批处理作业

我试图从EJB调用批处理作业.我的批处理工作基于javax.batch-api-1.0.jar,而不是spring.在我的ejb中,我使用以下行来调用批处理作业:

JobOperator jobOperator = BatchRuntime.getJobOperator();
Properties props = new Properties();
long execID=jobOperator.start("myBatch-job", props);
Run Code Online (Sandbox Code Playgroud)

然而,它失败了.Debug显示BatchRuntime.getJobOperator()返回null.谁能告诉我为什么调用失败了?谢谢.

=====问题应该是我没有将JobOperator注入EJB.但我不知道如何解决它.我尝试使用@Inject,

@Inject
JobOperator jobOperator;

...

Properties props = new Properties();
jobOperator.start("myBatch-job", props);
Run Code Online (Sandbox Code Playgroud)

我还添加了一个JobProducer类:

@Named
public class JobProducers {

    @Produces
    @Default
    public JobOperator getJobOperator() {
        return BatchRuntime.getJobOperator();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,它仍然无效.

ejb java-ee batch-processing cdi

5
推荐指数
0
解决办法
717
查看次数

Java EE CDI拦截器无法在JAX-RS资源类中工作

我想在jax-rs资源类中使用分析拦截器.拦截器工作原理,但它会导致jax-rs资源类内部出现问题.我把演示代码放在github上.

这是对问题的描述.

首先,这是一个主要代码列表.

异形

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Profiled {
}
Run Code Online (Sandbox Code Playgroud)

探查

@Interceptor
@Profiled
public class Profiler {
    @Inject
    Logger logger;

    @AroundInvoke
    private Object profile( InvocationContext context ) throws Exception {
        long startTime = System.currentTimeMillis();
        try {
            return context.proceed();
        } finally {
            long time = System.currentTimeMillis() - startTime;
            logger.info( context.getMethod() + " took " + time + " milliseconds" );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

UtilsProducer

public class UtilsProducer {
    @Produces
    private Logger createLogger( InjectionPoint point ) { …
Run Code Online (Sandbox Code Playgroud)

java glassfish jersey cdi jboss-arquillian

5
推荐指数
1
解决办法
4900
查看次数

@ApplicationScoped在一个集群中

我目前没有集群环境,但我很好奇 @ApplicationScoped集群环境中的行为.群集中是否只有一个群集,或者群集中每个JVM仍然只有一个群集?

我已经读过@Singleton根据JVM创建的内容

如何在群集环境中使用javax.ejb.Singleton?

java cluster-computing cdi

5
推荐指数
1
解决办法
776
查看次数

Java CDI.Interceptor仅在类的第一个方法调用中调用

我正在使用CDI拦截器,我意识到只有在使用@Interceptor注释的类中的第一个方法调用才会被截获.在下面的示例中,方法B从未被截获.

@InterceptorBinding
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Transactional {

}


@Transactional
@Interceptor
public class TransactionsInterceptor {

    @AroundInvoke
    public Object transactionInterceptor(InvocationContext context) throws Exception {

          System.out.println("Method="+context.getMethod().getName());
          return context.proceed();

    }
}


public Interface AnImportantInterface {
      public void methodA();
      public void methodB();
}

@Transactional
@ThreadScoped
public class AnImportantClass implements AnImportantInterface {

    public void methodA() {

        methodB();
    }

    public void methodB() {

        //This method is never intercepted
    }

}


public class AnotherImportantClass {
    @Inject AnImportantInterface aui;

    public void someMethod() {
        aui.methodA();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果首先调用methodA,我怎样才能截获该方法?有一些解决方法吗?

java interceptor cdi

5
推荐指数
1
解决办法
2262
查看次数

如何将参数传递给CDI中另一个类的注入类?

我是CDI的新手,曾试图找到此问题的解决方案,但没有发现任何问题。问题是,假设我有一个正在注入的类(A),正在注入一些值(toPass),现在我想将此相同的值(toPass)传递给B类,而B类是从A类注入的。

public class A 
{
    String toPass = "abcd"; // This value is not hardcoded

    @Inject
    private B b;
}

public class B 
{
    private String toPass; 
    public B(String toPass)
    {
        toPass = toPass;
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?注意:我们无法以与在A中初始化相同的方式来初始化B的toPass变量,对此有一些限制。基本上在春季,我们可以轻松做到这一点,但我想在CDI中完成。

java dependency-injection inject parameter-passing cdi

5
推荐指数
1
解决办法
2579
查看次数

CDI不在从工厂模式实现创建的对象中工作

我试图在这里解决一些问题:注入仅适用于我的应用程序的第一层,但随后它停止,并且从我的工厂模式实现返回的对象中所有@Inject注释属性都为null.我读了很多关于让CDI与JAX-RS一起工作有问题的人,但这似乎不是我的问题.我觉得我错过了一些注释,或者我没有看到所有树木前面的木头(正如我们在这里所说);-)

编辑:是否有一个示例项目与我在这里发布的代码进行仔细检查.现在我意识到我过度简化了:事实上我正在使用工厂模式来获取我的服务,这可能会中断托管上下文.请参阅增强示例:

我们走吧.

第一层:JAX-RS应用程序,一切都很好

@RequestScoped
@Path("/somePath/someResource")
public class SomeResource {
   @Inject
   ISomeServiceFactory someServiceFactory;

   @POST
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes(MediaType.APPLICATION_JSON)
   public SomeResponse someMethod(@PathParam("foo") final String foo) {
      ISomeService myService = someServiceFactory.getService(ServiceCatalog.valueOf(foo));   // works, we jump in there!
      myService.someMethod();
   }

}

public enum ServiceCatalog {
  STANDARD("standard"), ADVANCED("advanced"), FOO("foo");
  // ...
} 
Run Code Online (Sandbox Code Playgroud)

正在从REST API调用中选择基于已知参数(Enum)值的实现的已损坏服务工厂:

public interface ISomeServiceFactory {
  public ISomeService getService(ServiceCatalog serviceType);
} 

@Stateless
public class SomeServiceFactory implements ISomeServiceFactory {
  public ISomeService getService(ServiceCatalog serviceType) { …
Run Code Online (Sandbox Code Playgroud)

ejb java-ee cdi websphere-liberty

5
推荐指数
1
解决办法
620
查看次数

当WAR文件部署中包含的JodaTime v.2.5库失败时

当WAR文件中包含的JodaTime v。2.5库在GF 5.0中部署失败时,出现以下错误。看来问题出在hibernate-validator中。GF5.0在运行GF 4.1.2时,hibernate-validator捆绑包未加载ReadableInstant,因此未加载FutureValidatorForReadableInstant。

加载应用程序时发生异常:CDI部署失败:Errornstantiating:org.hibernate.validator.cdi.internal.ValidationExtension

Caused by: java.lang.TypeNotPresentException: Type org.joda.time.ReadableInstant not present
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.repository.ClassRepository.getSuperclass(ClassRepository.java:90)
at java.lang.Class.getGenericSuperclass(Class.java:777)
at org.hibernate.validator.internal.util.TypeHelper.resolveTypeForClassAndHierarchy(TypeHelper.java:386)
at org.hibernate.validator.internal.util.TypeHelper.resolveTypes(TypeHelper.java:351)
at org.hibernate.validator.internal.util.TypeHelper.extractType(TypeHelper.java:327)
at org.hibernate.validator.internal.engine.constraintvalidation.ClassBasedValidatorDescriptor.(ClassBasedValidatorDescriptor.java:39)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorDescriptor.forClass(ConstraintValidatorDescriptor.java:49)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.hibernate.validator.internal.metadata.core.ConstraintHelper.putConstraints(ConstraintHelper.java:686)
at org.hibernate.validator.internal.metadata.core.ConstraintHelper.(ConstraintHelper.java:386)
at org.hibernate.validator.internal.engine.ValidatorFactoryImpl.(ValidatorFactoryImpl.java:155)
at org.hibernate.validator.HibernateValidator.buildValidatorFactory(HibernateValidator.java:38)
at org.hibernate.validator.internal.engine.ConfigurationImpl.buildValidatorFactory(ConfigurationImpl.java:322)
at org.hibernate.validator.cdi.internal.ValidationExtension.(ValidationExtension.java:116)
... 78 more
Run Code Online (Sandbox Code Playgroud)

hibernate-validator cdi bean-validation

5
推荐指数
1
解决办法
1258
查看次数