Springを引き続き使用する場合は、@Component
を使用して簡単なコンポーネントを作成できます。デフォルトでは、すべてのコンポーネントはシングルトンです。 @PostConstruct
を使用してデータを初期化することができます。以下は例です。私はString
をマップキーとして使用していますが、アプリケーションに合わせて変更することができます。
@Component
public class MyMap {
private Map<String, Object> theMap = new HashMap<>();
// PostConstruct runs after the application context instantiates the bean
@PostConstruct
public void init() {
// initialize the data in theMap
}
public Object get(String key) {
return theMap.get(key);
}
}
あなたはその後、Beanを取得するために@Autowired
注釈やアプリケーションコンテキストを使用することができます。
public class AnotherClass {
@Autowired
MyMap myMap;
// ...
}
あなたが春を避けたい場合は、別のオプションは、単純なJavaシングルトンを作成することです。ここで注意すべき
public class MyMap {
private final static Map<String, Object> theMap = new HashMap<>();
// Use a static block to initialize the map with data
static {
// populate theMap with data
}
public Object get(String key) {
return theMap.get(key);
}
}
一つのことは、あなたのマップがこれまで実際に更新されますない場合、その後、あなたは同時読み取りおよび更新を処理する必要があるということである例です。
デフォルトでは、Spring Beanはシングルトンです。ちょうどそれを春の豆にして、それを必要な場所に注入してください。 –