我正在尝试使用@ApplicationScoped
@ManagedBean
调用和计划任务,该任务将每 2 秒将一些属性加载到我的 JSF 应用程序中。由于某种原因无法正常工作。请参阅我遵循的步骤。
我做的第一件事是创建一个每 2 秒从文件系统加载一次的类:
@ManagedBean
@ApplicationScoped
public class ProppertyReader {
@PostConstruct
public void init(){
SystemReader systemReader = new SystemReader();
systemReader.schedule();
}
private class SystemReader {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private Logger LOGGER = Logger.getLogger(ProppertyReader.class.getName());
public void schedule(){
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Properties properties = loadProperties();
LOGGER.info("Loaded property enabled:" + properties.getProperty("enabled"));
}
}, 0L, 2L, TimeUnit.SECONDS);
}
private Properties loadProperties() {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("~/Desktop/propertiesRepo/example.properties"));
return properties;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
然后我转到另一个 bean 并尝试使用该属性:
@ManagedBean
@SessionScoped
public class SomeBean {
//...
private Properties properties = new Properties();
private boolean enabled = new Boolean(properties.getProperty("enabled"));
//...
public boolean isEnabled() {
return enabled;
}
}
当我尝试在 JSF if 语句中使用一些 bean 来#{someBean.enabled}
根据该值显示或隐藏组件时,似乎不起作用:
<c:if test="#{someBean.enabled}">
<h1>Works!</h1>
</c:if>
我不知道有什么问题,知道吗?
更新: 我看到了我的错误,与 Properties 类。我现在正在尝试创建那些没有被释放的属性,所以我清理了一些代码,但是当应用程序启动时我得到了一个 NullPointer。
我将属性阅读器分为 2 个类:
@ManagedBean
@ApplicationScoped
public class ProppertyReader {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private SystemReader systemReader = new SystemReader();
public static Properties appProperties;
@PostConstruct
public void init(){
schedule();
}
private void schedule(){
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
appProperties = systemReader.loadProperties();
}
}, 0L, 2L, TimeUnit.SECONDS);
}
}
这是我从系统读取的地方:
public class SystemReader {
public Properties loadProperties() {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("~/Desktop/propertiesRepo/example.properties"));
return properties;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
我现在的称呼是:
@ManagedBean
@SessionScoped
public class SomeBean {
private boolean enabled = new Boolean(ProppertyReader.appProperties.getProperty("enabled"));
//...
目前我得到一个 NullPointer 异常,我想我已经接近了。