Java configuration framework [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential.
Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...

Apache Commons Configuration works great. It supports having the configuration stored in a wide range of formats on the backend including properties, XML, JNDI, and more. It is easy to use and to extend. To get the most flexibility out of it use a factory to get the configuration and just use the Configuration interface after that.
Two feature of Commons Configuration that differentiate it over a straight Properties file is that it support automatic conversion to common types (int, float, String arrays) and it supports property substitution:
server.host=myHost
server.url=http://${server.host}/somePath

If your hardcoded values are just simple key-value pairs, you should look at java.util.Properties. It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement.
If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution.
I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it.
Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.

Here are various options:
java.util.Properties
java.util.prefs.Preferences (since Java 5)
Commons Configuration
jConfig
JFig
Carbon's Configuration Service
You might want to read Comparison of Commons Configuration With JFig and JConfig and Configuring your Applications using JFig for some feedback from various users.
Personally, I've used jConfig and it was a good experience.

Commons Configuration
We're using this. Properties files alone are much easier to handle, but if you need to represent more complex data commons configuration can do this and read your properties files as well.
If you aren't doing anything complicated I'd stick to properites files.

If you want to do something advanced (and typesafe), you might want to take a look at this: http://www.ibm.com/developerworks/java/library/j-configint/index.html

the Intelligent Parameter Utilization Tool (InPUT, page) allows to externalize almost any (hard coded) decision as a parameter into an XML based configuration file. It has been initiated in early 2012 as a response to the perceived deficiencies in existing configuration tools with respect to generality, and separation of concerns.
InPUT is probably more powerful than most use cases require, as it allows for the programming language independent formulation of experimental data (input - output), with features such as the definition of complex descriptor to class mappings, or randomized configuration spawning and validation based on predefined value ranges (for test and research, e.g. Monte Carlo simulations). You can define parameters with sub parameters, relative restrictions on parameter values (numerical param a > param b) etc. .
Its still in beta, but rather stable, I use it for my research, for the configuration and documentation of experiments, and for teaching purposes. Once it is available for other languages (C++ adapter in the pipe), other researchers/practitioners can reuse the descriptors running their implementations of the same algorithms in C++ (using the code mapping concept). That way, experimental results can be validated/programs can be migrated more easily. The documentation is still in working process, but a couple of examples are available on the page. InPUT is open source software.
For those interested, the Conceptual Research Paper.

I tend to use java.util.Properties (or similar classes in other languages and frameworks) wrapped in an application-specific configuration class most of the time, but I am very interested in alternatives or variations on this. Especially since things can become a bit tricky if graphical configuration dialogs or multiple views on the configuration data is involved.
Unfortunately I don't have any experience with specific libraries for Java (except with the ones I have written myself), but any pointers would be appreciated.
Update
OK. That wasn't entirely true, three is the Spring Java Configuration Project.

I wrote about this a couple of weeks ago and came to the conclusion that XML is one of the most widely used notations.
Is it the best? I don't think so, I really like JSON, but the tooling is still not up to XML so I guess we have to wait and see.

You can try YamlBeans. This way you write whatever classes you want to hold your config data, then you can automatically write and read them to and from YAML.
YAML is a human readable data format. It has more expressive power than java.util.Properties. You can have lists, maps, anchors, typed data, etc.

Please take a look at this URL:
http://issues.apache.org/jira/browse/CONFIGURATION-394
The Configuration framework which we're looking for it is something on top of Apache Commons Configuration and must support Concurrency Issues, JMX issues and most of stores(e.g .properties file, .xml files or PreferencesAPI).
What weblogic team provides on 'Administration Console' is intersting which through it you can have transactional(atomic) updates on configurations so that are registered listeners be notified.
The Apache guys insist that this project is out of scopes of Commons Configuration, maybe!
I've attached a simple configuration framework, take look please.

I just posted a brief bit of code about using Spring's ClassPathResource as an alternative to IoC. ClassPathResource permits you to place property files anywhere on the classpath (e.g., all in one place, or as peers to the code they configure. My example just uses java.util.Properties, so you can use the plaintext "name=value" style or its XML format.

Properties files a very simple, if you need something more functional, you could format some of your configuration files as Java classes. These can be placed in a different package/module and can be pre-compiled or loaded at runtime with a library like BeanShell.
Note: In the simplest case (pre-compiled) you don't need any additional libraries.

Regarding the suggestions to use java.util.Properties - starting in jdk 1.5, the Preferences API (java.util.prefs) appears to be the preferred alternative to using the Properties API.
Reasons: increased scalability, back-end neutrality, ect.

You could have a look at newly announced tools4j-config whose mission statement is to allow you to easily handle configuration at runtime.

Related

Multiple language support in Spring project without using multiple message_language.properties files

I want to add different languages support in my Spring Web-MVC application without adding message_language.properties file for each language.
But I found message_language.properties file solution everywhere.
I searched deeply but I haven't got any solution for it.
please suggest me any solution....
Its not clear what are the reasons why you search for a different solution. Perhaps not what you want, but many projects that require dynamic language addition use database backed resource bundles (technically speaking its the solution without the properties file, but essentially the approach is the same).
If this is what you want you can check out the blog http://www.webreference.com/programming/Globalize-Web-Applications15_Java_ResourceBundles/index.html.
The following stackoverflow could be helpful as well
Database backed i18n for java web-app

Annotations vs XML, advantages and disadvantages [duplicate]

This question already has answers here:
Xml configuration versus Annotation based configuration [closed]
(16 answers)
Closed 9 years ago.
i am new to java here, I was reading about annotations and xml, personally I find out xml has lot of advantages like it can be put outside application, changes can be made without recompiling class files. If i use annotations if I need to make changes need to go to source code and recompiling should be done. If this is the case why should we use annotations
Advantages of the annotation:
1) All the information is in a single file (no need to open two files to configure a given behavior)
2) When the class changes, no need to modify the xml file
Advantages of xml file:
1) Clear separation between the POJO and its behavior
2) When you do not know which POJO is responsible for the behavior, it is easier to find that POJO (searching in a subset of files rather than all the source code)
First of all we use annotations for many more things, than just configuration.
Now: Some advantages of using annotations for configuration
Readability. For example in JPA configuration its much more cleaner to declare new entities by Annotations instead of hbm.xml files. These things change only in development stage so there is no problem with recompiling code. When You use xml files You have to often open both- entity and hbm file to make changes.. That can cause some errors.
Flexibility. In XML files you have to write all configs in "only one proper way". It is advantage and disadvantage at the same time.
Length. XML-based configs are often very long (like pom's, or hbm's). Annotations are much simpler to use.
The question is actually a difficult one to answer in a short answer.
Basically, there are pros and cons to all forms of configuration. Annotations, xml or Java Based Configuration. All the pros and cons are 100% valid. The main goal them becomes consistency. Making sure everyone on your project follows the same rules.
It is also NOT a question of either or, which one over the other. Because you can use any combination of configuration options in your application. One or all three combined. You just have to make your rules and stick to them
So my personal opinion is. Remember this is all my opinion and not fact.
1) Annotations over all other because I can configure and code much faster
2) Java Based configuration for those beans I can't annotate (They aren't my classes so I don't have the source to add an Annotation)
3) xml with what is left, or I need it complete externalized outside the package of my classes and I don't want to recompile and repackage. (Extremely rare, like it has never happened to me yet that I needed this)

Spring annotation-based DI vs xml configuration?

Recently in our team we started discussing using spring annotations in code to define spring dependencies. Currently we are using context.xml to define our dependencies. Would you give me some clues for either approach, and when one is better to be used?
Edit: I know this seems a duplicate question to a more-general one, but I am interested in the impacts of annotations vs configuration for dependency injection only, which I believe would have different answers and attitude than the general question.
After reading some related posts here and having further discussion in the team we come to the following conclusions. I hope the would be useful to others here.
About XML configuration (which we are using up to now), we decided to keep it for dependencies defined by libraries (regardless if being developed by us, or by third parties).
Libraries, by definition, provide a particular functionality and can be used in various scenarios, not necessarily involving DI. Therefore, using annotations in the library projects we develop ourselves, would create a dependency of the DI framework (Spring in our case) to the library, making the library unusable in non-DI context. Having extra dependencies is not considered a good practice among our team (an in general IMHO).
When we are assembling an application, the application context would define the necessary dependencies. This will simplify dependency tracking as the application becomes the central unit of combining all the referenced components, and usually this is indeed where all the wiring up should happen.
XML is also good for us when providing mock implementations for many components, without recompiling the application modules that will use them. This gives us flexibility when testing running in local or production environment.
In regards to annotations, we decided that we can benefit using them when the injected components will not vary -- for instance only a certain implementation for a component will be used troughout the application.
The annotations will be very useful for small components/applications that will not change or support different implementations of a dependency at once, and that are unlikely to be composed in a different way (for instance using different dependencies for different builds). Simple micro-services would fit in this category.
Small enough components, made up with annotations, can be used right out of the box in different projects, without having the respective applications to cover them in their XML configuration. This would simplify the application dependency wiring for the application and reduce repetitive setups.
However, we agreed that such components should have the dependencies well described in our technical documentation, so that when assembling the entire application, one can have an idea of these dependencies without scrolling through the code, or even loading the module in the IDE.
A negative side effect of annotation-configured components, is that different components could bring clashing transitive dependencies, and again it is up to the final application to resolve the conflicts. When these dependencies are not defined in XML, the conflict resolution approaches become quite limited and straying far from the best practices, if they are at all possible.
So, when going with annotations, the component has to be mature enough about what dependencies it is going use.
In general if our dependencies may vary for different scenarios, or a module can be used with different components, we decided to stick to XML. Clearly, there MUST be a right balance between both approaches, and a clear idea for the usages.
An important update regarding the mixed approach. Recently we had a case with a test framework we created for our QA team, which required dependencies from another project. The framework was designed to use the annotation approach and Spring configuration classes, while the referenced project had some xml contexts that we needed to reference. Unfortunately, the test classes (where we used org.testng with spring support) could only work with either the xml or java configuration classes, not mixing both.
This situation illustrates a case where mixing the approaches would clash and clearly, one must be discarded. In our case, we migrated the test framework to use spring xml contexts, but other uses could imply the other way around.
Some advantages of using XML configuration:
The XML configuration is at one place, instead of being scattered all over the source code in case of annotations. Some people may argue that IDEs like STS allow you to look at all annotations based configuration in one place, but I never like having dependencies on IDEs.
Its takes a little more efforts to write XML config, but it saves a lot of time later when you search for dependencies and try to understand the project.
XML keeps configuration well organized and simple. Hence is easier to understand, it helps new relatively inexperienced team members get up to speed quickly.
Allows you to change the config without a need to recompile and redeploy code. So it is better, when it comes to production support.
So in short XML configuration takes a little more efforts, but it saves you a lot of time & headache later in big projects.
2.5 years later:
We use annotations mostly these days, but most crucial change is that we create many small projects (instead of a one big project). Hence understanding dependencies is not a problem anymore; as each project has it's unique purpose and relatively small codebase.
from my experience, I would prefer(or rather am forced by limitations) to use a combination of XML and annotation based DI . If I need to inject a Map of elements inside a bean , I would have to define a util:map and autowire it . Also, I need to use XML DI to inject datasource into the sessionFactory if I have multiple datasources and so on . So a combination of both would be requited .
I prefer the usage of component-scan to autodetect the services and Dao . This cuts down a lot of Configuration (We cut down the configuration files by around 50% switching to component-scan). Annotation based DI supports both byName(#Resource) and byType(#Autowired).
In short my advice to be to go for a fixture of both . I feel that more annotation support will definitely be on cards in future Spring releases.
Take a look at this answer here: Xml configuration versus Annotation based configuration
A short quote directly from there:
Annotations have their use, but they are not the one silver bullet to
kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for
the dependency injection portion of your application. This gets the
code's dependencies away from the code which will be using it, by
contrast, using some sort of annotation in the code that needs the
dependencies makes the code aware of this automatic configuration.
However, instead of using XML for transactional management, marking a
method as transactional with an annotation makes perfect sense, since
this is information a programmer would probably wish to know.
EDIT: Also, take a look at the answers here: Java Dependency injection: XML or annotations They most probably target the area of your interest much better.
From my own experience annotations better than xml configuration. I think in any case you can override xmls and use annotations. Also Spring 4 give us a huge support for annotations, we can override security from xml to annotations e.t.c, so we will have not 100 lines xml but 10 lines Java Code.
Are annotations better than XML for configuring Spring?
The introduction of annotation-based configurations raised the
question of whether this approach is 'better' than XML. The short
answer is it depends. The long answer is that each approach has its
pros and cons, and usually it is up to the developer to decide which
strategy suits them better. Due to the way they are defined,
annotations provide a lot of context in their declaration, leading to
shorter and more concise configuration. However, XML excels at wiring
up components without
touching their source code or recompiling them. Some developers prefer
having the wiring close to the source while others argue that
annotated classes are no longer POJOs and, furthermore, that the
configuration becomes decentralized and harder to control.
No matter the choice, Spring can accommodate both styles and even mix
them together. It’s worth pointing out that through its JavaConfig
option, Spring allows annotations to be used in a non- invasive way,
without touching the target components source code and that in terms
of tooling, all configuration styles are supported by the Spring Tool
Suite.
my personal option is that xml is better since you have all at one place and you do not need to deep into your packages to search the class.
We can not tell which method is good, it depends on your project. We can nither avoid xml nor annotation. One advantage of using xml is that we can understand the project structure just seeing the xml context files, but annotation reduces lots of meta configuration. So I prefer 30% xml and 70% annotation.
By using XML, you prevent code from being polluted with framework-specific annotations and thus creating an undesired coupling. Keep the framework at the application boundary so you can always replace it should the need arise.
Frameworks come and go, but many applications live for decades. Fortunately, Spring is a non-invasive framework and doesn't bend your architecture. Keeping the configuration in XML will make it even more detached from your application.
Remark: in order to benefit from all this, your application should be well-designed in the first place.

Are annotations some sort of DSL in Java?

After a bunch of XML config files, I've seen Java moving to Annotation based configurations.
Are annotations playing the role of DSL here?
Is it because the static nature of Java? I'm thinking in Ruby which doesn't have ( afaik ) things like that. Is it because Ruby has good metaprogramming capabilities?
Are there alternatives ( I mean other than using a bunch of .xml files )
Basically annotations are a tool that allows you to process source files at compile-time and do action corresponding to annotations found in the file (possibily deriving a new source).
They are quite useful for many purposes like expliciting constraints while avoiding cluttering the code or enrich the behaviour of some methods.
I wouldn't say that they are so similar to DSLs of Ruby since in this case you annotate code with a particular syntax while in Ruby you can design your own DSL from scratches and use it as you wish.
Java ships a tool called apt (like the one you suspect) that is able also to work with annotations at run-time but they are usually used to give compile-time infos to your sources. This doesn't mean that in certain circumstances you can't easily adapt the annotation mechanism to work out the same things that you would obtain with a DSL but they don't exist for the same purpose.
As already said, annotation can be used to create DSLs quite efficiently, bacause they add some sort of metaprogramming capabilities to the langauge. However for that purpose you could use byte code injector or even any other Java language feature.
However the primary purpose of annotations is to be able to annotate source code elements with metadata.
If you are asking for alternatives for creating internal DSLs in Java, just look at the Fowler's DSL book WIP and choose from different concepts which can be used for implementing internal DSLs, many of them are present in Java. If you are asking for alternatives for metaprogramming, then there are also many: different byte code injectors, aspect oriented programming using AspectJ or Spring or code generation.

What's Up with Logging in Java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Why one would use one of the following packages instead of the other?
Java Logging
Commons Logging
Log4j
SLF4j
Logback
In chronological order of api apperance (as far as I know):
Log4j because most everybody uses it (in my experience)
Commons Logging because open source projects use it (so they can integrate with whatever logging framework is used in the integrated solution); especially valid if you're an API/Framework/OSS and you rely on other packages that use Commons Logging.
Commons Logging because you don't want to "lock down" to a particular logging framework (so instead you lock down to what Commons Logging gives you instead) - I don't think it is sensible to decide using this point as the reason.
Java logging because you don't want to add in an extra jar.
SLF4j because it's newer than Commons Logging and provides parameterized logging:
logger.debug("The entry is {}.", entry);
//which expands effectively to
if (logger.isDebugEnabled()){
// Note that it's actually *more* efficient than this - see Huxi's comment below...
logger.debug("The entry is " + entry + ".");
}
Logback because it's newer than log4j and again, supports parameterized logging, as it implements SLF4j directly
SLF4j/Logback because it's written by the same guy who did log4j, so he's made it better (according to Ken G - thanks. It seems to fit when looking at their earlier news posts)
SLF4j because they also publish a log4j adapter so you don't have to "switch out" log4j in older code - just make log4j.properties use SLF4j and it's configuration
I find logging in Java to be confusing, inconsistent, poorly documented, and especially haphazard. Moreover, there is a huge amount of similarity between these logging frameworks resulting in duplication of effort, and confusion as to what logging environment you are actually in. In particular, if you are working in a serious Java web application stack, you are often in multiple logging environments at one time; (e.g hibernate may use log4j, and tomcat java.util.logging). Apache commons is meant to bridge different logging frameworks, but really just adds more complexity. If you do not know this ahead of time, it is utterly bewildering. Why are my log messages not printing out to the console, etc.? Ohh because I am looking at the Tomcat logs, and not log4j. Adding yet another layer of complexity, the application server may have global logging configurations that may not recognize local configurations for a particular web application. Lastly, all these logging frameworks are WAY TOO COMPLICATED. Logging in Java has been a disorganized mess leaving developers like me frustrated and confused.
Early versions of Java did not have a built-in logging framework leading to this scenario.
There's one important point that wasn't mentioned before:
SLF4J (and both Logback and LOG4J as the logging backend) have support for a so called Mapped Diagnostic Context (MDC, see javadoc and documentation).
This is essentially a thread-local Map<String,String> which you can use to add additional context information to your logging event. The current state of the MDC is attached to every event.
This can be incredibly useful if you put stuff like the username and the URL of the request (in case of a webapp) into it. This can be done automatically using a filter, for example.
See also answers to the question What are the best practices to log an error?, especially:
There are some potential
classloading issues with Commons
Logging.
Log4J and SLF4J were developed by
the same person, learning from
issues found in practice with Log4J.
In our company project we use LOG4j and it is very easy to use like Stephen showed in his example.
We also have written our own pattern classes for LOG4j so you can create your own output file schemas. You can describe how your log file should look like. It is possible to enhance the original log4j classes.
All LOG4j properties you can change in a log4j.properties file, so you can use different files for different projects.
Java logging is not my favorit, but this could be because i use log4j from the beginning.
The Commons Logging overview gives the reason for its existence: logging from library code, when you have no control over the underlying logging framework. Very important for the various Apache projects, which will be linked into outside applications. Perhaps not so important for internal IT projects, where you have complete control.
That said, I write to Commons Logging, as do many of the other developers I know. The reason is to minimize mental baggage: you can change projects or jobs, and not have to learn a new framework (provided the new job/project also uses CL, and/or you can convince them to move to it).
Also, there is some value to creating your own wrappers around whatever framework you use. As described here, I like to use a LogWrapper object to provide custom stringification (important), and minimize the visual clutter of logging statements (less important).
Generally I would default to using Log4J.
I would use Java Logging if I didn't mind a dependency on Java 1.4 but I would still use Log4J in preference.
I would use Commons Logging if I was enhancing something that already used it.
I would suggest creating a thin logging facade that can write to any of the logging frameworks, at which point the choice of backing engine become pretty much a moot point.

Categories

Resources