Use Spring module without using Spring and Maven? - java

I'm currently working on a project that involves building a REST api using JavaEE. The setup of the project is Tomcat, Hibernate, Wink and Jackson Json for the different json-views. At the moment the unit testing of the rest resources is very poor, we've written custom classes that using introspection find the method that corresponds to a given resource but it is getting in our way (all the workarounds that we need to do in order to execute a simple unit test). I did a little research and found this.
My question is how to "install(add)" the MockServletInvocationTest class and its dependencies to the project? We're not using Maven, nor Spring. Is there a way to use Spring modules (I think this mock class is in the Spring test-module) outside Spring and if yes, how?

I found a solution, so for those who are interested: just add the following jars to your WebContent/WEB-INF/lib:
spring-test-xx.jar
spring-core-xx.jar
wink-component-test-support-xx-incubating.jar
commons-logging-xx.jar
And everything workds fine.

Related

Spring initialiser dependencies for a REST consumer console application

I am a Spring Boot newbie. I'd like to initialise a project which consists of:
A console application that acts on command line arguments so the JAR files could be later used in scheduled tasks.
Consumes a RESTful service
Logging
Which package dependencies should I choose in Spring Initializer? Apart from the necessary packages, are there any libraries that are optional but make development easier?
Depends on how you want to consume the restful service, but you may not need any extra starters, the core spring-boot-starter that you get when you just hit "Generate Project" and is usually implied with all the common starters like -web, -security, .. has logging and dependency injection and is all you need to create a jar that can easily be started with java -jar
However, it does not come with RestTemplate which is a common way to build rest clients in spring. For that you'll need to manually add a dependency on org.springframework:spring-web like you can see examples for in https://spring.io/guides/gs/consuming-rest/
But you can as well use other rest client libraries if you like them better.
There is also Feign that can be used as rest client and it's available from the initializer, examples at https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html - have not tried it and I'm not sure how much extra cloud dependencies will be added when you add the starter.
I also like having Lombok in all projects but that's preference. The obvious sounding choice of DevTools doesn't give you much benefit in a console application but is great for live reloading of web servers.
[...] so the JAR files could be later used in scheduled tasks.
sounds like you're trying to create a library / module of a larger application. You don't need an application that works standalone for that though so maybe https://spring.io/guides/gs/multi-module/ is good to read for you. Difference for libraries is that you don't need the spring boot plugin for maven/gradle which can package a standalone jar, just the dependency management.

How to restrict autos scanning of src/test/java in Spring Boot?

I have created a simple web app by following the book "Mastering Spring MVC". Everything was working fine, however, during the testing chapter, I have created two beans with #Primary annotation. 1. ProviderSignInController and 2. An Impl of my search service class. Both of these are in package src/test/java.
The problem here is that if I deploy my application, even then, these two beans come into the picture and I am not able to work with my actual authentication and search service.
I am not getting any error or exception. I would like to know what could be the best way to automatically inject my mocks/stubs while testing and actual implementations when I deploy the app in my dev environment.
The source code link is here. Thanks.
Instead of #Primary, I'd suggest using #Profile("PRODUCTION") along side #Bean for your real/production beans/classes & #Profile("!PRODUCTION") with your test beans/classes. Then, specify the active profile(s) at runtime
-Dspring.profiles.active=PRODUCTION, ...
The problem was the way I was executing the application.
When I launched the application directly from eclipse (Run As Spring Boot App), the tests were included in the build as they were present in the classpath.
I modified my approach and now I am using gradle build (gradle bootRun) to launch my app. This solves the problem. Thanks to #DwB for providing the hint.

Have I to put spring-mvc.jar in my classpath to create a Spring MVC project?

I am pretty new in Spring. If I want to implement a Spring MVC project have I to explicitly put the spring-mvc.jar file into my classpath? From what I know the Spring MVC project is not part of the Spring Core.
Is it right?
You can go many ways but I'll suggest you to learn a build automation tool like maven or gradle. It will take care of everything related to dependency management. Here's a good resource to get started https://spring.io/guides/gs/gradle/

Should I use the Spring Framework jar files or Spring Batch jar files while creating a java email batch program?

I am trying to create a java email batch program that sends an email with an attachment each day to a specific email address, and I have to use Spring as the framework for this program. It is not going to be a web application, but since I'm implementing Spring into this, how would I go about this? I am totally new to Spring (and Java for that matter), but am unsure of which direction I need to go. Which jar files do I need? Spring Batch or Spring Framework? Also, where can I download the jar files for Spring Framework? The spring.io site won't let me download those jar files.
I very strongly suggest you use a build tool that handles dependency management. Such tools are Ant+Ivy, Maven and Gradle. They will take care of downloading the appropriate jars based on your declaration of what dependencies you need and will take care of all the transitive dependencies.
One good way of getting started with Spring Batch is to follow this tutorial using either Maven or Gradle (the latter would probably be easier since you don't need to install it - the tutorial's code has a wrapper).
The tutorial uses Spring Boot which vastly simplifies Spring configuration (which is a serious benefit especially for someone who is new to Spring)
As others already told you, I personally would not start any spring based project (means: any project) without maven! You have so much benefits from it, not only depencency management.
To start a spring app outside an application context:
#Configuration
public class AppConfig {
//any bean configurations here
}
//your entry class
static void main(String args[]) {
//get a reference to the spring context. use this context throughout your app!
ApplicationContext ctx = new AnnotationConfigApplicationContext(CacheConfig.class).get();
//optain any beans from the context. inside these beans, you can use any spring feature you like, eg #Autowired
ctx.getBean(YourBean.class).executeMethod();
}
I'd recommend starting with Spring Boot which will handle all of that for you. As others have mentioned, pick a build tool (Maven or Gradle) and follow the guide we provide on building a batch application here: http://spring.io/guides/gs/batch-processing/.

Practical advice on using Jersey and Guice for RESTful service

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.

Categories

Resources