Where do you store a persistent memory value (non db) over the lifetime of an app?
Let's say I want to set a variable when my Spring app is instantiated:
S开发者_如何转开发tring timeUp = new Date().toString();
I want to be able to access this value from all of my app's beans but I don't want to store it in a database. I just want to save it in a bean in the app that will be accessible from all other beans in the app. How is this possible?
If everything lives on the same machine, you may want to use a singleton. It's a single instance which everything can easily access and call.
For long term storage, if a database isn't an option, you may want to serialize your bean to a file, or simply write your own file format and output to that.
Spring Beans are, by default, Singletons. So just create a bean for this purpose.
@Component
public class TimeUp {
private final String _timeUp = new Date().toString();
public String getTimeUp() { _timeUp };
}
Then inject this bean where you need it.
@Component
public class Whatever {
@Autowired TimeUp timeUp;
public void useTimeUp() {
System.out.println(timeUp.getTimeUp());
}
}
A singleton initialized in a ContextListener
's contextInitialized
method would be my first point of call.
one way of doing this would be to let one of your servlet classes or filter classes have a public static final member of type Date and on the declaration line set it to a new date object. then you can do "servlet class name (dot) public member name" to access this value.
if you do it in a servlet, you must declare that servlet inside your web.xml as a "load-on-startup" servlet. otherwise it won't get its date value until the first time that servlet is used, and that's not really what you want :)
If you actually just want the apps uptime, you should be able to use the following
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
long uptimeInMillis = mx.getUptime();
If you are looking for a more abstract answer, then Chris gave a good solution.
This is a classic use of a singleton. If you have only a few of these, you can create a singleton per value. If you have a bunch of these, you can write a 'service' where you set and lookup values.
In spring, you can do this:
import org.springframework.beans.factory.FactoryBean;
public class TimeUp implements FactoryBean<String> {
private final String _value = new Date().toString();
public String getObject() {
return _value;
public Class<?> getObjectType() {
return String.class;
}
public boolean isSingleton() {
return true;
}
}
Then in Spring, you would simply do:
<bean id="timeUp" class="example.TimeUp"/>
You can use a Singleton:
public class Environment {
private final long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
public long getStartTime() {
return this.startTime;
}
private static final Environment SINGLETON = new Environment();
private Environment() {
//nop
}
public static Environment getInstance() {
return SINGLETON;
}
}
精彩评论