Guice 学习(六)使用Provider注入服务( Provider Inject Service)
1、定义接口
package com.guice.providerInject;
import com.google.inject.ProvidedBy;
public interface Service {
public void execute();
}
2、定义实现类
package com.guice.providerInject;
public class OneService implements Service {
@Override
public void execute() {
System.out.println("Hello! I'M Service 1!");
}
}
3、Provider实现类
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();
}
}
4、ProviderServiceDemo 測试类
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!
}
}
5、ProviderServiceDemo2測试类
假设不想使用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(); //发现不起作用不知何解 ?
}
}
6、ProviderServiceDemo3測试类
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!
}
}