Google guice注入了Spring创建的实例和方法拦截

时间:2013-04-25 15:47:57

标签: aop guice code-injection

我使用Gucie 3.0拦截任何具有我定义的注释@LogRequired的方法。但是对于我的应用程序,Spring会使用注入的字段值初始化一些bean。在调用giuce injector.injectMembers(this)之后,bean被guice代理,但所有原始字段值都消失了。看起来像Guice重新构建bean并抛弃所有旧值。这是预期的行为还是如何解决这个问题?

创建一个类extends AbstractModule

public class InterceptorModule extends AbstractModule{ public void configure() 

{LogInterceptor tracing = new 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()); }

我有一个下面的bean示例,getName方法希望被拦截:

public class UserImplTwo implements IUser {

private String name;


    @LogRequired
public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}
}

由Spring上下文初始化:

最后我有一个使用bean的消费者:

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:

 <bean id="consumer" class="com.demo.Consumer" init-method="init">
    <property name="instance" ref="userTwo"></property>
</bean>

如果这是正确的方法或我做错了什么,请告诉我,因为我必须使用Spring初始化一些bean。

1 个答案:

答案 0 :(得分:0)

A&#34;正确的方法&#34;如果你使用Spring Framework,可能会保持简单并使用Spring的DI,而不是试图与Guice混合搭配: - )

话虽如此,似乎没有技术上的理由说明为什么他们不能在某种程度上混合在一起。

我认为你会用另一种方法取得更大的成功。我之前使用的一个是使用Spring MVC基于Java的配置。这是基本方法。

创建一个扩展WebMvcConfigurationSupport的类:

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

将你的bean配置分开(可能它可以与上面的内容合并,但我想它的代码非常枯燥,你通常不想看到它)。并且在将它们提供给Spring之前,使用它来使用Guice注入器创建bean。

@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。