package com.ilucky.guice.test10;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
/**
* v1.0:20161114
* @author IluckySi
*
* 注解@Provides.
* 当使用@Provides方法创建对象时,该方法必须定义在Module类中,并且它必须加以@Provides注解,
* 该方法的返回值类型就是被绑定的对象.当注入器需要该类型的实例时,它就会来调用该方法.注意:Provides和Provider的区别.
* @Provides方法绑定方式是可以和注解绑定混合使用的.
* 如果在@Provides方法上有绑定注解(@AnnotationOne),Guice以绑定注解优先.
* Guice在调用@Provides方法之前会先解析该方法的依赖.
*/
public class MainTest {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MyModule());
MyService myService = injector.getInstance(MyService.class);
myService.service();
MyService myServiceOne = injector.getInstance(Key.get(MyService.class, AnnotationOne.class));
myServiceOne.service();
MyService myServiceTwo = injector.getInstance(Key.get(MyService.class, AnnotationTwo.class));
myServiceTwo.service();
System.out.println("-----------------@Provides的使用--------------------------");
Injector injector2 = Guice.createInjector(new MyModule2());
MyService myService2 = injector2.getInstance(MyService.class);
myService2.service();
}
}
/**
==>one
==>one
==>two
-----------------@Provides的使用--------------------------
==>xxx
*/
package com.ilucky.guice.test10;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;
public class MyModule implements Module{
public void configure(Binder binder) {
binder.bind(MyService.class).to(Key.get(MyService.class, AnnotationOne.class));
}
@Provides @AnnotationOne
public MyService one() {
return new MyService("one");
}
@Provides @AnnotationTwo
public MyService two() {
return new MyService("two");
}
}
package com.ilucky.guice.test10;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provides;
public class MyModule2 implements Module{
public void configure(Binder binder) {
}
@Provides
public MyService xxx() {
return new MyService("xxx");
}
}
package com.ilucky.guice.test10;
public class MyService {
private String type;
public MyService(String type) {
this.type = type;
}
public void service() {
System.out.println("==>" + type);
}
}
package com.ilucky.guice.test10
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
import com.google.inject.BindingAnnotation
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface AnnotationOne {
}
package com.ilucky.guice.test10
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
import com.google.inject.BindingAnnotation
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface AnnotationTwo {
}