SpringのMessageSourceをオーバーライドして、データベース(現在はSQLite)からメッセージソースを取得しています。
CachedMessageSourceDao.java(Subject)に示されているように、insertMessageが呼び出されるたびにCachedMessageSource.java(Observer)が通知されます。オブザーバーパターンだから!!
CachedMessageSourceDao.java(Subject)を初期化することを除いて、すべて正常に動作します。
DualKeyMap MESSAGES <-最初に通知されなくても、これは埋められる必要があります。
しかし、私はどのように実装するのか分かりません。このためにどのデザインパターンが機能するか教えてください。
ApplicationContext.xml
<bean id="cachedMessageSourceDao" class="org.springframework.context.support.CachedMessageSourceDao">
<constructor-arg name ="dataSource" ref="dataSource" />
<constructor-arg name="DATABASE" value="BytoCms"/>
<constructor-arg name="TABLE" value="MessageSource"/>
<constructor-arg name="USE" value="1" type="int"/>
<constructor-arg name="NOT_IN_USE" value="0" type="int"/>
<constructor-arg name="ALL" value="99" type="int"/>
<constructor-arg name="messageSource" ref="messageSource" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.CachedMessageSource" />
CachedMessageSource.java(オブザーバー)
public class CachedMessageSource implements MessageSource, Observer {
/** Message Storage */
private static DualKeyMap<String, Locale, String> MESSAGES;
...more
@Override
public void update(Observable o, Object arg) {
try {
MESSAGES = ((CachedMessageSourceDao) o).selectAllMessages();
} catch (SQLException e) {
System.out.println("Message Initializing Failed");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
CachedMessageSourceDao.java(件名)
public class CachedMessageSourceDao extends Observable {
private DataSource dataSource;
private String DATABASE;
private String TABLE;
private int USE;
private int NOT_IN_USE;
private int ALL;
public CachedMessageSourceDao(
DataSource dataSource,
String DATABASE,
String TABLE,
int USE,
int NOT_IN_USE,
int ALL,
CachedMessageSource messageSource) {
this.dataSource = dataSource;
this.DATABASE = DATABASE;
this.TABLE = TABLE;
this.USE = USE;
this.ALL = ALL;
this.NOT_IN_USE = NOT_IN_USE;
addObserver(messageSource); //★add Observer★
notifyObservers(); //★This for initializing★
}
...more
public synchronized void insertMessage(String code, String value, String language) throws Exception {
//Duplicate Message Check
if(selectMessage(code, language) != null) throw new SQLException("Duplicate message exists for code: " + code + " and" + "language: " + language);
String sql = "INSERT INTO " + TABLE + " (code, value, language, flag) values (?, ?, ?, " + USE + ")";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(true);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, code);
pstmt.setString(2, value);
pstmt.setString(3, language);
pstmt.execute();
} catch(SQLException ex) {
ex.printStackTrace();
} finally {
try {
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
notifyObservers(); //Realtime apply to MessageSource
}