Annotation base configuration in standalone Java program - java

I was made aware with the annotation base configuration (the #Resource) feature in Java EE which I really like. Then I noticed that the annotation was actually part of Java SE.
So I wonder if I can use it with Java SE. I can surely use the annotation in a standalone program but I am find how to actually configure it. All the examples I found involve creating a Java EE configuration file. Can any one give me a confirmation (or give me a reference to one) that it can be used outside of Java EE environment? and how to do that?

Annotations have specific purposes and can only be used for those purposes. So Java EE annotations will in most cases have no function outside Java EE. But for instance jUnit and JPA annotations should work in a Java SE applications. You can also roll your own if you feel like it.

I'm thinking the same thing. Something must process annotations--this is what Spring does, but currently I'm not using Spring.
It wouldn't be too difficult to add custom annotation processing to handle the #Resource, #PostConstruct and #PreDestroy annotations (It would probably be a few dozen lines of code) but at some point you gotta think "Well, Spring is already doing all that and a heck of a lot more".
They are also implemented by Tomcat for WebServices, so you can just use them but only on properly configured #WebService classes.

Related

Interceptor API : in a classic java project

I want to add a listener on java method and I saw the annotation #Interceptors and #AroundInvoke.
I want to use it in a classic java project but all tutorials show me Java EE projects.
Is it possible ?
Interceptor is a DI (Dependency injection) concept based on AOP (aspects oriented programming).
Since Java-ee 6 you have a lightweight DI container named CDI.
You can use CDI in a java-se context if you provide an implementation allowing a standalone deployment like jboss weld :
See Is it possible to use javax.interceptor in a Java SE environment?
Otherwise, you can use spring, which also provides a lightweight DI container with the same kind of features and may be better suited for a java-se context usage.
I don't think so, those are managed by the Java EE container.
An easy way is to create a proxy/wrapper over all instances of your class.
Or use Spring AOP (but you will have to configure Spring) or AspectJ.
Check this out: http://www.javacodegeeks.com/2012/06/simple-introduction-to-aop.html
Reading the doc here: https://docs.oracle.com/javaee/6/tutorial/doc/gkigq.html
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events.
So I guess the answer to your question is no.

Adding aspects to OSGi JAX-RS resources

I'm looking for a way to add certain functionality to JAX-RS resources in an OSGI environment. Annotations seem to be a clean way to do this and I've seen it done in the Spring framework (no experience). Annotations such as #Transactional, or (what I wanted to do, requires a permission flag to be set on a user) #Permission(CREATE). However, I'm a bit stuck on how to do this in an OSGI environment.
The normal way(is it?) to go about adding aspects would be to register an aspect service that wraps the original service. If I looked it up correctly, JAX-RS resources are tracked and hooked up to an HttpService. JAX-RS resources do not implement an interface and proxies would need to be dynamically created.
How would I dynamically generate OSGI aspect services/resources that effectively hide the original resource from the JAX-RS tracker that hooks it to the HttpService? I have zero experience with existing AOP frameworks and barely any knowledge of AOP itself.
It is very common in the Java EE and Spring world to use interceptors and define additional behavior based on annotations. There are some solutions in OSGi as well, there is an RFP to support EJB annotations.
However, I have a different opinion. Although this looks cool, it is also magical. See the "Why not annotations, interceptors and other magic?" chapter of this README file where I wrote down my reasons. This project implements the logic that you would like to achieve with #Transactional annotation, but it only uses functional interfaces.
I think it is better to think in lambda expressions to achieve the goal you want (see the java 8 example behind the link). If it is not Java 8, you can still use anonymous classes (see jave 7 and above example behind the link). Your code will look more ugly with anonymous classes, but it will be very clear, what your code does.
Others might not like my answer. Three years ago I was one of the biggest fan of annotation scanning, weaving and interceptors. After a couple of headaches, I became an enemy of this "magical" concept.

How can I make Seam Validation work outside a Java EE container?

I want to use Hibernate Validator's method parameter validation feature. From what I read in the documents, Hibernate Validator just offers an API, and I need the #AutoValidating annotation of Seam Validation to make things work.
However, I want to use the methd parameter validation outside a Java EE container, for plain methods, e.g. in utility classes.
What's the setup to get this to work?
For using method validation you need some sort of container creating and managing your objects, it doesn't neccessarily have to be Java EE, though.
If you are running in Java SE, you could e.g. use CDI and Seam Validation (the CDI reference implementation Weld can be used on SE) or alternatively the Spring framework, this post gives a good overview.
On GitHub you can also find a project of mine, showing the integration of method validation with Google Guice and also JDK dynamic proxies.
It is possible to build a Seam-based application living outside of a full-fledged Java EE container, for instance using a web container such as Tomcat. But anyway, Seam has to run in at least a web container, you can't use it outside for standalone applications (after all, Seam is a web applications framework). If you only need validations, consider using a simpler approach - for instance, try Apache's commons validator.

Best practices when using Spring 3 annotations

I'm looking for some best practices when using Spring 3 annotations.
I'm currently moving to Spring 3 and from what I've read so far I see a lot of accent placed on using annotations and moving away from XML configuration.
Actually what is recommended is a mix of both styles, with annotations covering things that won't change often or from one run to the next (e.g. a #Controller will remain like that for the life time of the application), while the things that change and must be configurable go into XML (e.g. a mail smtp address, endpoints for web services that your application talks to etc).
My question is what should go into annotations and to what extent?
At which point annotations make things harder instead of easier? Is the technology (Spring 3) fully adopted as to be able to make such statements or does it take some more time for people to gain experience with it and then reflect on the issue?
It is always difficult to get real advanced information.
The easy tutorial with "look on my blog, I copied the hello word tutorial from Spring Source website... Now you can put fancy annotations everywhere, it the solution of all of our problems including cancer and starvation." is not really usefull.
If you remember right spring core had several purposes, among them:
to be non intrusive
to change any
implementation/configuration of a
bean at any time
to give a centralized and controlled
place to put your configuration
Anotation fail for all theses needs:
They introduce coupling with spring
(you can use standard anotation only
but as soon as you have at least one
spring anotation this is no longer
true)
You need to modify source code and
recompile to change bean
implementation or configuration
Annotations are everywhere in your
code. It can be difficult to find
what bean will be really used just by
reading the code or XML configuration
file.
In fact we have shifted our focus:
We realized that we almost never
provide several implementations of
our services.
We realised that being dependant of
an API is not that bad.
We realized that we use spring not only
for real dependancy injection
anymore, but mainly to increase
productivity and reduce java code
verbosity.
So I would use anotations when it make sence. When it is purerly to remove boilerplate code, verbosity. I would take care of using the XML configuration file for thing that you want to make configurable, even if it is only to provide a stub implementation of the service in unit tests.
I use #Value for properties that are configured in external properties file via PropertyPlaceholderConfigurer, as kunal noted.
There is no strict line for when to use xml, but I use xml:
when the bean is not a class I control
when the object is related to the infrastructure or configuration rather than to the business logic.
when the class has some primitive properties that I would like configurable, but not necessarily via externalized configurations.
In response to your comment: spring is very widely adopted, but "good" and "bad" are very subjective. Even my lines are not universal truths. XML, annotations and programmatic configuration all exists for a purpose, and each developer / company have their preferences.
As I said - there is no strict line, and no universal good practice for annotations.
Annotations are surely the way by which "newer" programming in java will continue. I use annotations for various uses...like #Scope for scope of bean, #Required for making dependency necessary, #Aspect for configuring advices,#Autowired for constructor injection using annotations. Since spring 2.5, annotation support has been good.
See here for spring tutorial, where annotation based issue are covered here.
I think that two cases that the usage of annotations could cause some problems. Firstly, if you want to write complex named queries (JPA) in your entities. I saw some entity code samples and asked myself whether the code is really java code or not. To many metadata in program code will reduce the readability of it which kills clean code principles.
Second problem is portability between JVM versions. Annotation is a feature 1.5+. If your software should support earlier JVM versions, then you may not use these.
Anyway, you can enjoy with annotations everytime without having any doubt and spare your time not changing IDE tabs to check XMLs if the property is still there or not, or entered correct etc.
For very small projects you could still XML version if you haven't too many stuff to be declared in spring. But, if you are in a huge project, the things could be very troublesome if you had 10 xml configs.
This will perhaps not help you much but at work they don't want to use autowiring because it needs a classpath scan (but that can be package-defined i think). So it increases the startup time of the application according to the size of the project.

Is there a simple framework allowing for Dependency Injection in a stand alone program?

We basically need to be able to adjust behaviour at start-up time, by providing desired classes to be produced by various factories inside our application (to avoid the hard binding of the "new" operator).
I am aware that this is provided by several large frameworks, but I was looking for something easily used by a stand-alone Java application without being gigantic.
Any suggestions?
Edit: It is my experience that frameworks tend to grow big as part of maturing (and complex too). I need this to be retrofittable to a legacy application as part of major refactoring (technical debt), so simplicity is essential of the used libraries. I do not mind having to do a bit of coding in our application, but it must be very visible what is going on. AOP has a tendency for moving stuff out of the way, and that may make the application harder to maintain.
Edit: We have now reached the point where we actually need to make a decision. The application will probably live for decades so we need to make a reversible decision with a framework that will be maintained for hopefully as long. I really like the static type check available with Guice, but not that the annotations bind explicitly to Guice instead of being external like in Spring. I also like that code appears to be more concise when using Guice as opposed to Spring. We need something that is robust and helpful. We do not need more than just DI at the moment. Is there a use case that definitive says go for one of these?
Edit 2011-07-27: The final decision was to use the JSR-330 API in code, and choose on a per-project basis if to use Spring, Guice or Weld. For stand-alone applications Guice has worked well so far as the JSR-330 implementation.
You can always use Spring Framework 2.5. It is a big one, but if you planning to use only DI you can use spring-core and spring-beans modules, which are pretty small (ca. 500KB and 300KB).
There is also Google Guice 2.0 which comes with a package with only basic stuff (no AOP) and it's 430KB.
Have you looked at the Google Guice framework? It's pretty lightweight and annotation-based, avoiding XML configuration files
There's also Pico- and Nano-container (from codehaus) which are quite lightweight although the last time I looked (admittedly a few years ago) the documentation was lacking.
I must say that I agree with others about what I assume is your presumption that Spring is massive and confusing. It's really a very simple IoC container and to be recommended.
There are a couple I know of you might find useful:
PicoContainer
Plexus (used in Maven)
I've found Plexus very useful in standalone apps as it has optional utility components for CLI interaction.
By "gigantic" I'm going to assume you're referring to Spring, but that's unfair, since you can cherry-pick the bits of Spring you want to use. If all you need is the IoC container, just use the appropriate JAR files and the appropriate bit of the API, and ignore the rest of it.
Most answers so far seem to be concerned with the size of the jar files to be added.
However I think the more important question is the impact on the project: How many lines of code must be added/changed in order to use the framework?
Even the "big" spring framework is actually very easy to use:
You basically need:
a xml file that describes your factories.
one line of code to initialize the container by loading the xml file
The nice thing is that spring is non-intrusive. So you do not have to implement specific interfaces or add any specific annotations or imports to your classes.
At best the single spot where you actually initialize the Spring container is the only
place in your application that has an actual dependency to spring classes.
I would strongly suggest to take a look at Spring ME. Although originally meant to be a way to use Spring on Java ME applications, it also works fine for standalone applications.
True, it doesn't give you all of the bells and whistles that Spring (Full) has to offer, but then again, Full Spring is much much more than a simple dependency injection framework.
On the plus side: it's based on a (compliant) subset of Spring's configuration files, and the footprint of the runtime is 0%. In fact, there isn't any. Spring ME will take your application context, and turn it into a class that has no dependencies on classes other than your own.
What's wrong with Spring?
These days it's packaged pretty well so you wouldn't need to take the whole kit and caboodle.
As an aside, I'm not a fan of the annotation based injection frameworks. This is because the annotations are bound to the class rather than the instance, the later being a pre-requisite, imho, for DI. This means every instance of a given class gets the same object(s) injected, which seems to defeat the point.
Also consider that DI doesn't even need a framework, what's wrong with your main method wiring together the application?
If you want something maximally simple and appropriate, then write some code that does what you want done. Presumably this involves wiring together factories based partly on fixed logic, and partly on run-time settings.
This has the advantage that the set of possible run-time configurations is known, and so documentable and testable.
It has the disadvantage that an deploying an unanticipated logic change inherently takes an extra second or so of compile time, and (more significantly) can't be sneaked into production without full testing by disguising it as 'just a configuration change'.
About a year ago I asked myself a question very like this. So I spend a few hours reading the Spring and Guice documentation. After about an hour with Spring I was left feeling that I could get a basic web app going, but had no idea how to use it in a stand alone application. After an hour with the Guice document everything had clicked and I could see just how I to do what I wanted to get done.
Now on to recommending Guice? Well no. What does your team already know? If someone already knows say Spring leaver that knowledge and have them spread it about. Like wise with Guice or Pico.
If you want something really light weight you might want to have a look at fuse it's fairly extendable so might be what you're looking for.
cheers
N

Categories