package com.guice.providerInject;
import com.google.inject.ProvidedBy;
public interface Service {
public void execute();
}
package com.guice.providerInject;
public class OneService implements Service {
@Override
public void execute() {
System.out.println("Hello! I‘M Service 1!");
}
}
package com.guice.providerInject;
import com.google.inject.Provider;
/**
* TODO : 每次新建一个新的OneService对象出来
*
* @author E468380
*/
public class OneServiceProvider implements Provider<Service> {
@Override
public Service get() {
return new OneService();
}
}
package com.guice.providerInject;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Module;
/**
* 使用上面OneServiceProvider来新建实例 当然如果想自动注入(不使用Module手动关联)服务的话,可以使用@ProviderBy注解。
*
*/
public class ProviderServiceDemo {
@Inject
private Service service;
public static void main(String[] args) {
ProviderServiceDemo instance = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(Service.class).toProvider(OneServiceProvider.class);
}
}).getInstance(ProviderServiceDemo.class);
instance.service.execute();// Hello! I‘M Service 1!
}
}
如果不想使用Module手动关联服务的话,可以使用@ProviderBy注解。
package com.guice.providerInject;
import com.google.inject.ProvidedBy;
@ProvidedBy(OneServiceProvider.class)
public interface Service {
public void execute();
}
package com.guice.providerInject;
import com.google.inject.Guice;
public class ProviderServiceDemo2 {
public static void main(String[] args) {
ProviderServiceDemo2 instance = Guice.createInjector().getInstance(ProviderServiceDemo2.class);
// instance.service.execute(); //发现不起作用不知何解 ?
}
}
package com.guice.providerInject;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.Provider;
/**
* TODO :可以注入Provider而不是注入服务
* ◇由于我们OneServiceProvider每次都是构造一个新的服务出来,
* 因此在类ProviderServiceDemo3中的provider每次获取的服务也是不一样的。
*
* @author E468380
*/
public class ProviderServiceDemo3 {
@Inject
private Provider<Service> provider;
public static void main(String[] args) {
ProviderServiceDemo3 instance = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.bind(Service.class).toProvider(OneServiceProvider.class);
}
}).getInstance(ProviderServiceDemo3.class);
instance.provider.get().execute();// Hello! I‘M Service 1!
}
}
Guice 学习(六)使用Provider注入服务( Provider Inject Service)
原文地址:http://blog.csdn.net/u010834071/article/details/46708025