2013-04-25 62 views
0

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

回答

0

A「正確的做法」可能是讓事情變得簡單,如果你使用Spring框架使用Spring的DI,而不是試圖:-)

說了這麼多,似乎沒有技術上的原因,混合和匹配與吉斯它們不能在一定程度上混合在一起。

我想你會用另一種方法獲得更多的成功。我之前使用過的一個是使用Spring MVC基於Java的配置。這是基本的方法。

創建擴展WebMvcConfigurationSupport類:

@Configuration 
@Import(BeansConfig.class) 
public class Config extends WebMvcConfigurationSupport { 
} 

分離出來的豆配置(大概可以用上面的合併,但我想這是相當枯燥的代碼,你通常不希望希望看到它)。在將它們提供給Spring之前,用它來創建你的Guice噴嘴。

@Configuration 
public class BeansConfig { 
    @Bean 
    public Consumer getConsumer() { 
     return SomeGuiceInjectorFactory.newInstance(Consumer.class); 
    } 
} 

包括這在你的spring.xml(或引導其他方式,如果你的servlet容器是較新的比我是)

<context:annotation-config/> 
<bean id="extendedWebMvcConfig" class="Config"/> 

構造函數注入和大多數/所有?其他Guice善良也應該適用於這種情況。

你也不需要在xml中配置你的bean。