我正在使用 Jersey 2.5.1 创建一个休息 api。我正在使用 HK2 进行依赖注入。后来我决定使用 Apache Shiro 进行身份验证和授权。
在创建自己的自定义 Shiro Realm 时,我遇到了一些问题。在我的领域中,我想注入一个依赖项。但是,当我运行我的应用程序时,依赖项没有得到解决。
这是我的设置:
web.xml
<web-app 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/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>my.app.api.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
shiro.ini
[main]
authcBasicRealm = my.app.api.MyCustomRealm
matcher = my.app.api.MyCustomCredentialsMatcher
authcBasicRealm.credentialsMatcher = $matcher
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
[urls]
/** = authcBasic
我的应用程序.java
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new ApplicationBinder());
packages(true, "my.app.api");
}
}
ApplicationBinder.java
public class ApplicationBinder extends AbstractBinder {
@Override
protected void configure() {
bind(UserDAO.class).to(new TypeLiteral<Dao<User>>(){});
bind(RealDatasource.class).to(DataSource.class);
}
}
MyCustomRealm.java
public class MyCustomRealm extends JdbcRealm {
@Inject DataSource source;
public MyCustomRealm() {
super();
}
@PostConstruct
private void postConstruct() {
// postConstruct is never executed
setDataSource(source);
}
}
所以,问题在于 MyCustomRealm 中没有注入源。所有其他不是由 Shiro 创建的类都会注入其依赖项。问题可能是 Shiro 是通过 ini 文件创建我的 CustomRealm 吗?