我正在重写Spring的MessageSource以从数据库获取消息源(Currenly 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(Observer)
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
}