在 Java EE 6 中,有一个内置的 bean 类型javax.security.Principal
可用于注入,例如@Inject Principal principal;
.
这是默认情况下,我想知道是否有办法改变它,比如说,通过提供生产者方法。
就目前而言,编写生产者方法将导致部署异常。
示例生产者:
my.package;
import javax.security.Principal;
public class MyProducer {
...
@Produces
public Principal obtainPrincipal() {
return getMyPrincipal();
}
}
例外:
org.jboss.weld.exceptions.DeploymentException: WELD-001409 Ambiguous dependencies for type [Principal] with qualifiers [@Default] at injection point [[parameter 1] of [constructor] @Inject public my.package.MyType(Principal, SomeOtherType)]. Possible dependencies [[Producer Method [Principal] with qualifiers [@Any @Default] declared as [[method] @Produces @SessionScoped protected my.package.MyProducer.obtainPrincipal()], Built-in Bean [java.security.Principal] with qualifiers [@Default]]]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:278)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:244)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:107)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:127)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:346)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:331)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:83)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
所以问题是 - 有没有办法替换 CDI 中的默认内置类型?
为了让您了解我为什么需要它,我的项目正在从 JAAS 切换到 Apache Shiro。有大量现有代码基于注入的主体执行某些操作。然而,Web 环境中的 Shiro 仅包装 HttpServlet 请求/响应并覆盖适当的安全相关方法。然而,这不会传播到 CDI,在这种情况下,它总是返回匿名主体。
更新 我还尝试了以下方法:
my.package;
import javax.security.Principal;
@Alternative
public class MyPrincipal implements Principal {
...
@Override
public String getName() {
return getMyPrincipalName();
}
}
然后在 beans.xml 中启用替代方案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<alternatives>
<class>my.package.MyPrincipal</class>
</alternatives>
</beans>
在这种情况下,没有部署错误,但注入的主体仍然是默认的,而不是我启用的替代方案。