I can't get spring annotations to work at all, I'm just trying to get the simplest thing to work...
.../mycontext/something -> invokes method:
#RequestMapping(value = "/something")
#ResponseBody
public String helloWorld() {
System.out.println("hello world");
return "Hello World";
}
My main problem is no matter how hard I try, I can't find a complete SIMPLE example of the configuration files needed, every spring tutorial is filled with junk, I just one one controller to handle a request with a mapping and can't get it to work
does anyone know of a simple and complete spring example. pet-clinic is no good, it's way too complicated, I have a tiny basic use case and it's proving to be a real pain to get working (this always happens with Spring)
You should try Spring Roo. It will generate a simple Spring application for you using simple commands and then you can incrementally extend it. It is a great tool for learning Spring as well as for rapid application development.
You can also find several examples of Spring 3.0 MVC framework.
the absolute simplest alternative if you're familiar with Eclipse is to use SpringSource Tool Suite (Eclipse plugins)
This product has a tcServer bundled inside.
By default, STS will start with "dashboard" page in the editor window. From here, you can click on creating a controller as demonstrated by this screenshot:
This is a quite simple controller and all you have to do to get it deployed on the bundled tcServer (Tomcat with some extra management features) is to click "next" a few times in the wizard.
That's a very good starting point for doing your own testing!
I endorse this blog post,Layered architecture with Hibernate and Spring. It was a great help for me when I tried to move from the declared xml approach to annotations. It contains the usages of annotations in Entity, Dao and Service layers.
I'd recommend you checkout some of projects from here
and try going trough book spring in action(manning) they give very good example on how to use aspects
or refer to this question
Related
I'm going through the Spring right now and have some things on my mind. What is the point of doing so many things in the XML files? I've been through searching for the answer for this but found nothing interesting. I mean all those denpendency injections and declaring objects present way much better when written in Java, don't they? XML is not intuitive and there's aparently more code to write and I'm in the very beginning of my Spring path but I don't feel like this can be useful in the future... Can somebody explain to me what is so good about bringing programming to the XML? Or maybe pass me the link of some article which may help me? Thanks!
This is a complaint that comes from everyone who starts in Spring. It was way worse back in the 1.0 days. I have been doing XML configs in Spring and Struts for many years and have converted most if not all of my code to the new Spring annotated #Configuration and Springboot.
1) If you are new to Spring use Spring STS(Eclipse as your IDE) http://spring.io/tools ->Spring tool Suite.
2) Springboot - Remember that the whole idea behind Springboot is to get rid of all of what you are complaining about. Nearly all the configuration is done without XML.
3) Maven - The only real file you will need in XML is the POM.xml for your dependencies but Spring STS has a wrapper interface that will help you add dependencies as you go.
4) Pivital TC- When you start Spring STS you will notice it comes with Pivital's version of Tomcat.
5) File -> New-> Spring Starter Project: Select Web and Thymleaf(JSP replacement) I have lost my desire to code in JSP.
You will notice the DemoApplication.java class
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Notice that everything is now done without XML. The ApplicationContext.XM is now a simple Java class.
Springboot has a bunch of great new annotations that will take all the XML way :)
If there is something specific you want to do just add it in the comments below and I can guide you further. Thymeleaf is pretty simple you just add your HTML files in the /demo/src/main/resources/templates directory.
Good luck! Don't give up Spring is very powerful.
You have to look at the history behind the introduction of the Spring Framework as a better programming model than EJB2.x at the time it was introduced to understand where it is today. However, EE5, 6 and 7 have now changed radically to improve developer productivity, more convention over configuration, and use of annotations to indicate behavior of POJO classes.
Although Spring has been moving away from XML based configuration for a while and also using more annotations, you have to ask yourself at this point whether you'd rather Spring's implementation of JSR250 (Common Annotations) and JSR330 (Dependency Injection), or EE6 and 7, since both implement the same specs. There will probably be many heated replies to this point of view, but you have to take a good look at what it is you're trying to do before deciding on one verses the other. If you're planning on deploying a Spring based app to an EE6+ app server, then a pure EE solution might be the simplest and easiest approach.
I think ideally you wouldn't be programming in XML. In the end, it's not a programming language but a markup language.
I guess people use it because a markup language can be read and understood even by a person without a technical background, and also because processing an XML file is cheaper than calling the Java engine and using that in applications.
I am new with developing web application with Java Spring Framework inside Spring Tool Suite IDE. When start a new project there are so many kinds of project such as Spring Project, Simple Spring Utility Project, Spring VMC Template Project, Spring Roo Project, Static Web Project, Dynamic Web Project and Maven Project. I do not know which project I should select? Can someone explain me, please?
I would choose none of the above.
If you have a recent version of STS (since 3.4 I think) there is also an "Import Spring Getting Started Content" (clue in the name: if you are getting started this is a good place to look, and all the guides are online at https://spring.io/guides). If you are studying the guides then this is the best place to start.
You also get a "Spring Starter Project" option directly in the "New" menu. If you want a minimal project with enough code to run but no actual business logic, then this is the best place to start. It's what you would use to create the code in the guides mostly.
The other options (including all those listed in the original post) are unofficially deprecated, and not particularly well maintained or modern.
As an absolute beginner, I would read up on Spring Roo and then pick either Spring MVC or Spring Roo project depending on whether I liked Roo or not.
Spring MVC uses mainly annotations to configure its Controllers, as far as I know, the only way to configure a Controller in Spring WITHOUT Annotions (only XML) is extending the AbstracController (or Similar Controller classes) and currently all this classes are deprecated for Spring 3.
While I think that is a good idea to drop support for this classes, mainly because extending this classes creates controllers that hardly depend of Spring as a dependency, I don't understand why Spring doesn't provides a configuration like Struts Actions (Actions in Struts 2 don't extend any weird class so they dont' have any dependency of Struts)
Why Spring MVC doesnt provide a clean POJO-style configuration like Struts 2 Actions via XML?
Why to drop support for XML configuration on MVC using ugly Annotations? why not to drop it in ALL Spring Proyects?
The main problem with the XML/POJO approach is that there is no way to tell from looking at your code that special magic is going on.
Instead of seeing
#SomeAnnotation <<-- Oh, golly there is something special happening here.
java code...
You see
Java code <<-- special magic hidden in XML file (or not, no way to tell)
<<-- are these linked? no idea..
<<-- is something going on? let me go and search....
If changes happen to the source code, the XML may (or may not be) out of sync.
With the annotations you can update the java code and the spring annotations at the same time.
Yes it's cluttered but at least it's easy to sync the two.
Annotations are hard enough to grok when they're in your face. If they're not even visible the mental burden for us non-angry developers is really too much to bear.
why not to drop it in ALL Spring Projects?
Wouldn't that be sweet....
using ugly Annotations?
Obviously the question has been asked: Is there a way to hide annotations in Eclipse?
And the answer is: https://stackoverflow.com/a/2569646/650492
Sort of... does that help?
I have developed a REST API using Play! Framework 1.2.4, and I have a strong liking for the framework. The simplicity and the rapid development cycle helped me achieve this in a fraction of the time I would have taken had I gone the traditional Java EE route.
Now that I am exploring using Play! 2.0.3 for my next project. I see that while the framework has been enhanced and makes it even easier to develop web-apps, the same cannot be said about REST API's. My app will not have any HTML whatsoever - I will just respond with XML or JSON or whatever data exchange format I decide to use in future.
So, the question is:
Has anyone here used Play 2.0.x for exposing non-html pure REST API's?
More Details:
Here are some of the factors I feel make it more difficult to develop pure REST API's in Play 2.0.x compared to 1.2.x. Please correct my understanding if I am wrong.
Content Negotiation is harder
In play! 1.2.4, I content negotiation was build in to the framework. There were options to define right in the routes file what content-type a request expects.
GET /friends User.listFriends(format:'xml')
Then, in the controller,
public static void getFriends(){
render();
}
This would result in the views/xml/User/listFriends.xml template being rendered automatically. To add support for JSON tomorrow, all I needed to do was to add a views/json/User/listFriends.json template.
I do not see how this can be done in play! 2.0.x
Creating non-html templates is less intuitive
After some trial and error, I figured out that one can create, for example, a listFriends.scala.xml in the views folder in play! 2.0. Then, it needs to be invoked in the controller code as follows:
return ok(views.xml.listFriends.render());
However, Eclipse doesn't like this, because Eclipse does not know about the views.xml.listFriends since it is generated only after play compilation completes. Is there anything I'm missing here?
In Play (Scala) you can do something like this:
val myXMl = obtainXML();
return Ok(myXML).as("text/xml")
I'm not sure of the syntax in Java, but it would be equivalent: instead of creating a template, you generate the XML and then you send it to the user, setting the return type to "text/xml" (or json or whatever you need it to be).
As Pere Villega explained, but with the Java syntax:
String xml = getXMLAsString();
return ok(xml).as("text/xml");
The as() method is part of the Status class.
Or, an alternative is:
String xml = getXMLAsString();
response().setContentType("text/xml")
return ok(xml);
From what I can find online, the state of the art for Guice + Jersey integration has stagnated since 2008 when it appears both teams reached an impasse. The crux of the issue is that JAX-RS annotations perform field and method injection and this doesn't play nicely with Guice's own dependency injection.
A few examples which I've found don't go far enough to elucidate:
Iqbalyusuf's post on Jersey + Guice on Google App Engine Java suffers from a lot of boilerplate (manually getting and calling the injector). I want binding and injection should happen behind the scenes via Guice annotations.
Jonathan Curran's article Creating a RESTful service with Jersey, Guice, and JSR-250 gave me hope because it's much more current (2010), but went no further than showing how to start up a Jersey service inside of a Guice ServletModule. However, there are no examples of doing any real dependency injection. I suppose that was left as an exercise for the reader. Curran's post may in fact be the correct first step towards wiring up Guice and Jersey and so I plan on starting with that.
tantalizingly James Strachan writes:
JAX-RS works well with dependency
injection frameworks such as Spring,
Guice, GuiceyFruit or JBossMC - you
can basically pick whichever one you
prefer.
But I see no evidence that is true from a practitioner's point of view.
What I find lacking are practical examples and explanations on how to combine JAX-RS and Guice annotations. For instance:
I believe I cannot use constructor injection with any resource as Jersey wants to control this
I'm uncertain whether I can combine #Inject with #PathParam, #QueryParam, et al.
How to use injection in a MessageBodyWriter implementation
Does anyone have examples, preferably with source, of non-trivial application which combines Jersey and Guice without sacrificing one or the other in the process? I'm keeping on this road regardless, but the bits and pieces on the Jersey and Guice lists makes me think I'm repeating the work of others who came before me.
Guice integration with Jersey has not stagnated. The opposite is true. Thanks to Paul and his cohorts behind Jersey, the latest 1.7 release contains a special JerseyServletModule class to work with Guice-based servlets. Guice-based constructor injection into JAX-RS resource works! The issue is using JAX-RS annotations such as #QueryParam in the constructor of a JAX-RS resource. You don't need it! You use Guice for POJO injection all the way including singletons. Then JAX-RS is just icing on the cake for parsing HTTP-based RESTful APIs such as URL path, query parameters, content-type and etc. You don't need an "industrial strength" example either. Both Guice and Jersey are already battle tested. You just need a complete working example to see how it works. Then you can experiment advanced features on your own. Check out the following link for a complete example using Guice 3.0 and Jersey 1.7, which are all latest releases:
http://randomizedsort.blogspot.com/2011/05/using-guice-ified-jersey-in-embedded.html
I created a Guice/Jersey/Jetty/Jackson sample application here:
http://github.com/sunnygleason/j4-minimal
If you have any questions or suggestions for how to improve the
example, feel free to message me via github. The goal is to make
this a very accessible introduction to REST on the Java stack.
Hope this helps - have a great day!
-Sunny
Inspired by Sunnys sample application I've created a similar sample project that uses standard WAR files for deployment, e.g. in Apache Tomcat. You can find the project here:
https://github.com/danbim/template-guice-jersey-tomcat
Have fun!
Daniel
I believe I cannot use constructor
injection with any resource as Jersey
wants to control this
You cannot use guice's constructor injection because creation of resource is managed by jersey. In this case you can use jersey's #Inject annotation before constructor parameter you want to get injected:
public NewsResource(#Inject NewsService service)
I was having similar problems initially trying to use Guice to do constructor injection on my Jersey annotated classes, but eventually got it working, albeit with a fairly trivial application.
I followed the instructions here: jersey-guice javadoc
The trick in my case was that I needed to remove the standard Jersey configuration from my web.xml (like the Jersey ServletContainer) and keep only the Guice listener and Guice filter. Once I did that Guice was being called to create my JAX-RS annotated object, and Jersey was injecting my JAX-RS annotated methods (like #GET, etc.) as expected.
Although Sunny Gleason's example is great, it is a bit outdated now.
So, after struggling a lot today trying to make Guice and Jersey play nice with each other, I created the following sample project to get you started:
https://github.com/MaliciousMustard/gradle-guice-jersey-jetty
This project is using the following technologies:
Guice for DI
Jersey for the RESTful API
Jackson for POJO to JSON mapping
Jetty for the web-server
Gradle
I guess the most important thing is that you don't have to explicitly specify every new resource class you're adding. As long as you're adding them to the package that is being scanned (look at malicious.mustard.modules.JerseyModule), they will be found automatically!
GWizard includes a module that gives you out-of-the-box integration between Jersey2 and Guice. Here's an example of a complete JAX-RS service:
public class Main {
#Path("/hello")
public static class HelloResource {
#GET
public String hello() {
return "hello, world";
}
}
public static class MyModule extends AbstractModule {
#Override
protected void configure() {
bind(HelloResource.class);
}
}
public static void main(String[] args) throws Exception {
Guice.createInjector(new MyModule(), new JerseyModule()).getInstance(Run.class).start();
}
}
Note that this is based on the Squarespace jersey2-guice adapter, which may not function properly with future point releases of Jersey. GWizard also offers a RESTEasy JAX-RS module, which is preferred.
Here is a blog entry about this that might help: http://blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way
The Jersey-Guice plugin Javadoc provides a pretty good description:
http://jersey.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/com/sun/jersey/guice/spi/container/servlet/package-summary.html
These examples were all great starts for me, but I wanted a full MVC stack using Jersey-Guice at it's core. I've been working on refining that for sometime. As of this week this MVC stack is fully deployed to Maven Central repository as an archetype. This means you can now create a new Jersey-Guice stack with one Maven command:
mvn archetype:generate \
-DarchetypeGroupId=org.duelengine \
-DarchetypeArtifactId=duel-mvc-archetype \
-DarchetypeVersion=0.2.1
This automatically generates your own project with you specified package naming so you don't have to manually edit a template project.
See the project Readme.md for more details: https://bitbucket.org/mckamey/duel-mvc
Details on the dual-side views (client-side template & server-side views) I use are here: https://bitbucket.org/mckamey/duel but you could replace with whatever you use.
I found an interesting project for lightweight Jetty+Guice+Jackson web services: https://github.com/talis/jersey-common/
I created a Guice 4.2, Jetty 9.4 and Jersey 2.7 sample application:
https://github.com/bnsd55/jetty-jersey-guice-starter-kit
As Sunny said:
If you have any questions or suggestions for how to improve the
example, feel free to message me via github. The goal is to make this
a very accessible introduction to REST on the Java stack.