相关疑难解决方法(0)

CDI:跨不同模块/ bean归档使用拦截器

我的Java EE 6应用程序由war文件和ejb模块组成,包含在ear文件中.我正在使用CDI for DI(即我在两个模块中都有一个beans.xml文件).我想使用war模块中的ejb模块中定义的日志拦截器.我在ejb的beans.xml中启用了拦截器:

<beans>
    <interceptors>
        <class>com.test.interceptor.LoggingInterceptor</class>
    </interceptors>
</beans>
Run Code Online (Sandbox Code Playgroud)

这仅适用于使用ejb模块中的拦截器注释的类.战争模块中的类不被截获(尽管它们也被拦截器注释).我认为解决方案是在战争的拦截器中启用拦截器(如上所述).但是无法使用以下消息部署应用程序:

严重:加载应用程序时出现异常:WELD-001417启用拦截器类类com.test.interceptor.LoggingInterceptor既没有注释@Interceptor也没有通过可移植扩展注册

我的LoggingInterceptor看起来像这样:

@Log
@Interceptor
public class LoggingInterceptor {
    private static final Logger logger =  Logger.getLogger(LoggingInterceptor.class.getName());

    static {
        logger.setLevel(Level.ALL);
    }

    @AroundInvoke
    public Object logMethod(InvocationContext ctx) throws Exception {
        logger.log(Level.FINE, "ENTRY {0} {1}",
                new Object[]{ ctx.getTarget().getClass().getName(), ctx.getMethod().getName() });
        long startTime = System.nanoTime();
        try {
            return ctx.proceed();
        } finally {
            long diffTime = System.nanoTime() - startTime;
            logger.log(Level.FINE, "RETURN {0} {1}",
                new Object[]{ ctx.getTarget().getClass().getName(), ctx.getMethod().getName() });
            logger.log(Level.FINE, "{0} took {1} ms", …
Run Code Online (Sandbox Code Playgroud)

java-ee interceptor cdi ejb-3.1

16
推荐指数
3
解决办法
1万
查看次数

使用CDI注入命名字符串

我希望以这种方式注入配置参数:

public class MyManagedBean {
    @Inject
    public MyManagedBean(@Named("user") String user){
        ....

    }
}
Run Code Online (Sandbox Code Playgroud)

所以我尝试用这种方式实现一个生成器方法:

@ApplicationScoped
public class MyConfiguration {
    private Properties loadProperties() {
        Properties properties = new Properties();
        try {
            properties.load(getClass().getResourceAsStream(
                    "user.properties"));
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return properties;
    }

    @Produces
    @Named("user")
    String getUser() {
        return loadProperties().getProperty("user");
    }
}
Run Code Online (Sandbox Code Playgroud)

我有这样定义的其他bean:

public class OtherManagedBean {
    @Inject
    public OtherManagedBean(MyManagedBean myManagedBean){
        ....

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试部署它时,我遇到了这个异常:

INFO: WEB0671: Loading application [example-ear#example-war.war] at [example]
SEVERE: Exception while loading the app
SEVERE: …
Run Code Online (Sandbox Code Playgroud)

java string dependency-injection named cdi

7
推荐指数
1
解决办法
3330
查看次数