相关疑难解决方法(0)

使用CDI注入命名字符串

我希望以这种方式注入配置参数:

public class MyManagedBean {
    @Inject
    public MyManagedBean(@Named("user") String user){
        ....

    }
}
Run Code Online (Sandbox Code Playgroud)

所以我尝试用这种方式实现一个生成器方法:

@ApplicationScoped
public class MyConfiguration {
    private Properties loadProperties() {
        Properties properties = new Properties();
        try {
            properties.load(getClass().getResourceAsStream(
                    "user.properties"));
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return properties;
    }

    @Produces
    @Named("user")
    String getUser() {
        return loadProperties().getProperty("user");
    }
}
Run Code Online (Sandbox Code Playgroud)

我有这样定义的其他bean:

public class OtherManagedBean {
    @Inject
    public OtherManagedBean(MyManagedBean myManagedBean){
        ....

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试部署它时,我遇到了这个异常:

INFO: WEB0671: Loading application [example-ear#example-war.war] at [example]
SEVERE: Exception while loading the app
SEVERE: …
Run Code Online (Sandbox Code Playgroud)

java string dependency-injection named cdi

7
推荐指数
1
解决办法
3330
查看次数

标签 统计

cdi ×1

dependency-injection ×1

java ×1

named ×1

string ×1