我使用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。