@ApplicationScoped
@ManagedBean
2 秒ごとにいくつかのプロパティを JSF アプリにロードする to call およびスケジュールされたタスクを使用しようとしています。何らかの理由で機能していません。私が従う手順を参照してください。
最初に、ファイル システムから 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;
}
}
#{someBean.enabled}
その値に応じてコンポーネントを表示または非表示にするために JSF if ステートメントで使用する Bean を使用しようとすると、動作しないようです。
<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 例外が発生していますが、近づいていると思います。