Extending Butterfly Container Script With Constants
It is possible to define constants in Butterfly Container Script (BCS). What you do is simply to define a factory that returns a constant value. Here are a few examples:
sessionTimeout = 1 10000; url = 1 "http://jenkov.com"; connectionTimeout = 1 com.myapp.Constants.CONNECTION_TIMEOUT;
The "sessionTimeout" factory is defined as a singleton returning the value 10000. This will by default be a long, but the container will convert it if injected into a method or constructor that requires an int, short etc.
The "url" factory is defined as a singleton returning the string "http://jenkov.com". This factory can be referenced whereever a string can be injected.
The "connectionTimeout" factory is defined as a singleton returning whatever value the CONNECTION_TIMEOUT constant is set to in the Constants class. By returning the value of a constant defined in your Java code it is possible keep all constant definitions in your Java code, if desired.
Referencing these constants is done like you reference any other factory in BCS. Here are a few examples referencing the factories above:
bean1 = * com.myapp.SessionManager(sessionTimeout); bean2 = * java.net.URL(url); bean3 = * com.myapp.ConnectionManager(connectionTimeout);
Constants as Singletons
You might have noticed that all the constants are defined as singletons. Whether you define them as new instance factories or singleton factories won't affect the correctness of your application, since the values are constants. However, defining them as singletons will speed up instantiation a bit after the first instantiation, because the constant value remains cached in the singleton factory. You may not notice this speedup in your application though, if the constant is not referenced often.