我是Guice的新手,这是一个天真的问题.我了解到我们可以通过以下方式将String绑定到特定值:
bind(String.class)
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza");
Run Code Online (Sandbox Code Playgroud)
但是如果我想将String绑定到任何可能的字符呢?
或者我认为可以这样描述:
如何用Guice替换"new SomeClass(String strParameter)"?
Nam*_*ter 42
首先需要为构造函数注释SomeClass:
class SomeClass {
@Inject
SomeClass(@Named("JDBC URL") String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用自定义注释,如下所示:
class SomeClass {
@Inject
SomeClass(@JdbcUrl String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface JdbcUrl {}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要在模块中提供绑定:
public class SomeModule extends AbstractModule {
private final String jdbcUrl; // set in constructor
protected void configure() {
bindConstant().annotatedWith(SomeClass.JdbcUrl.class).to(jdbcUrl);
}
}
Run Code Online (Sandbox Code Playgroud)
然后GUice创建SomeClass,它将注入参数.例如,如果SomeOtherClass依赖于SomeClass:
class SomeOtherClass {
@Inject
SomeOtherClass(SomeClass someClass) {
this.someClass = someClass;
}
Run Code Online (Sandbox Code Playgroud)
通常,当您认为要注入String时,您希望注入一个对象.例如,如果String是URL,我经常注入带有绑定注释的URI.
这都假设您可以在模块创建时为String定义一些常量值.如果在创建模块时该值不可用,则可以使用AssistedInject.
Geo*_*org 20
这可能是偏离主题的,但Guice使配置比为所需的每个String编写显式绑定更容易.你可以为他们配置一个配置文件:
Properties configProps = Properties.load(getClass().getClassLoader().getResourceAsStream("myconfig.properties");
Names.bindProperties(binder(), configProps);
Run Code Online (Sandbox Code Playgroud)
并且所有配置都准备好注入:
@Provides // use this to have nice creation methods in modules
public Connection getDBConnection(@Named("dbConnection") String connectionStr,
@Named("dbUser") String user,
@Named("dbPw") String pw,) {
return DriverManager.getConnection(connectionStr, user, pw);
}
Run Code Online (Sandbox Code Playgroud)
现在只需在类路径的根目录下创建Java属性文件 myconfig.properties
dbConnection = jdbc:mysql://localhost/test
dbUser = username
dbPw = password
Run Code Online (Sandbox Code Playgroud)
或者将来自其他来源的授权信息合并到属性中并进行设置.
| 归档时间: |
|
| 查看次数: |
30756 次 |
| 最近记录: |