In the previous example, the Android Roboguice use Guide (4): Linked bindings for simplicity, defining MyRectangle and MySQUARE defines a constructor that takes no parameters, such as MyRectangle, as follows:
public class MyRectangle extends rectangle{public
myrectangle () {
super (50,50,100,120);
}
public myrectangle (int width, int height) {
super (50,50,width,height);
}
You can actually do without this constructor without arguments, you can use Instance bindings, Instance bindings can bind a type to a particular instance object, typically to a type that does not depend on other classes, such as a variety of basic types, such as:
Bind
(String.class)
. Annotatedwith (names.named ("JDBC URL")
. ToInstance ("jdbc:mysql://localhost/ Pizza ");
Bind (Integer.class)
. Annotatedwith (names.named ("Login timeout Seconds"))
. ToInstance (10);
The definitions for modifying MyRectangle and MySQUARE are as follows:
public class MySQUARE extends MyRectangle {
@Inject public
mysquare (@Named ("width") int width) {
super ( width,width);
}
...
The public class MyRectangle extends rectangle{
@Inject
the public MyRectangle (@Named ("width") int width,
@Named ("height") int height) {
super (50,50,width,height);
}
}
With a parameterless constructor, you can bind the int type labeled @named ("width") to 100, adding the following bindings:
Bind (Integer.class)
. Annotatedwith (names.named ("width"))
. toinstance (MB);
Bind (Integer.class)
. Annotatedwith (names.named ("height"))
. ToInstance (120);
To run this example, you can get the same result as the previous example. When using injector to construct a MyRectangle instance, injector automatically selects the constructor with the parameter, using 100,120 as the width and height injection parameters, returns a MyRectangle object to the place that needs to be referenced.
Although you can use instance bindings to map a type to a class instance of a complex type, Roboguice does not recommend applying instance bindings to instances of complex types, because it slows down the application startup.
The correct approach is to use the @Provides method, which is described below.
Note: the example in Guicedemo does not use a list method to display all the examples, and if you need to run the required samples, you can set up the launch activity through run Configuration->:
View a full set of articles: Http://www.bianceng.cn/OS/extra/201301/34950.htm