我使用Gucie 3.0拦截任何具有我定义的注释@LogRequired的方法。然而,对于我的应用程序,一些bean由Spring注入字段值进行初始化。在调用giuce injector.injectMembers(this)之后,bean会被guice代理,但所有的原始字段值都消失了。看起来Guice重新构建了这些bean并丢弃了所有的旧值。这是预期的行为还是我该如何解决这个问题?Google guice注入一个由Spring创建的实例和方法拦截
创建类扩展AbstractModule
public class InterceptorModule extends AbstractModule{ public void configure()
{7.LogInterceptor纪录跟踪=新7.LogInterceptor纪录(); requestInjection(跟踪); bindInterceptor(Matchers.any(),Matchers.annotatedWith(LogRequired.class),tracing); } }
定义拦截业务逻辑
public class LogInterceptor implements MethodInterceptor { //business logic here }
创建LogService类
Public class LogService { Injector injector = Guice.createInjector(new InterceptorModule()); }
我有下面的GetName方法要被拦截的bean的实例之一:
public class UserImplTwo implements IUser {
private String name;
@LogRequired
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
由Spring上下文初始化:
最后我有一个消费者消费豆:
public class Consumer
{
@Inject
private UserImplTwo instance;
public void setInstance(UserImplTwo instance)
{
this.instance = instance;
}
public void init()
{
// the value of name is printed out as 'hello world'
System.out.println( this.instance.getName());
LogService.injector.injectMembers(this);
// the value of name is printed out as null, should be 'hello world'
System.out.println( this.instance.getName());
}
}
然后使用Spring来初始化豆:
<bean id="consumer" class="com.demo.Consumer" init-method="init">
<property name="instance" ref="userTwo"></property>
</bean>
请让我知道这将是正确的做法,或者如果我做有什么不对,因为我必须使用Spring来初始化一些bean。