2013-04-25 69 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。