Để ngăn chặn bao giờ lặp lại tiêm của cùng một giá trị tạo ra một trường không tĩnh trong một lớp được khởi tạo rất thường xuyên, tôi thích tạo một Singleton ConfigUtil đơn giản như một cách giải quyết:
package de.agitos.app.util;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
/**
* Helper class to get injected configuration values from static methods
*
* @author Florian Sager
*
*/
@Configurable
public class ConfigUtil {
private static ConfigUtil instance = new ConfigUtil();
public static ConfigUtil getInstance() {
return instance;
}
private @Value("${my.value1}") Integer value1;
public Integer getValue1() {
return value1;
}
}
Bên trong lớp tôi đã cố gắng để đưa các giá trị đầu tiên như một Integer tĩnh:
private static Integer value1 = ConfigUtil.getInstance().getValue1();
Nguồn
2013-05-14 10:53:07
Nếu bạn yêu cầu thay thế: ngữ cảnh là gì? – Ralph