Are there any differences for #Context injected on a Class or a Method? - jersey

In JAX-RS we can inject #Context instances like HttpServletRequest as a class field or as a method parameter.
Are there any differences between those two options?
I belive Singletons will have some sort of proxy injected instead, but are there any side-effects to be aware of? Or are they transparent and it's just a matter of personal taste?

For the most part, it is simply personal preference.
My advice would be to inject as class fields, as the #Context annotation will eventually be replaced by #Inject from CDI - and the #Inject annotation does not target method parameters. You can read more of the discussion here.

#Inject and #context have different targets. #Inject cannot be used for params and #context cannot be used in constructors. A very popular use case for #context is indeed in param position.
The majority of JAX-RS resource methods use #context in param position, except for the entity. This would need to be converted to an #Inject at method level, but would make things less clear regarding the entity param. There's also the issue of ContextResolver's which are somewhat similar to CDI producers and would need tweaking.
We can check Java doc:
#Context: #Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
#Inject: #Target({ METHOD, CONSTRUCTOR, FIELD })
It depends on your usage contex.

Related

#Autowired or private final

My question is simple. Which approach is more efficient?
method 1:
#Autowired
private CustomerRepository customerRepo;
method 2:
private final CustomerRepository custormerRepo;
public StudentService(CustomerRepository customerRepo) {
this.customerRepo = customerRepo;
}
As I see the DI in the method2 is more recent. But I wanted to ask you which one should I use?
TL;DR: Method 2 is much more flexible.
Method 1 is an example of field injection and method 2 is an example of constructor injection.
Field injection has some drawbacks that constructor injection avoids. Here are some advantages of constructor injection:
Immutability:
You can't do this is plain Java:
#Autowired
private final CustomerRepository customerRepo;
// No constructor that sets "customerRepo".
So, Spring offers constructor injection:
private final CustomerRepository customerRepo;
#Autowired
public StudentService(final CustomerRepository customerRepo) {
this.customerRepo = customerRepo;
}
Immutability is sometimes preferred. One reason is that it helps with thread-safety. Another is security.
Personally, I follow the rule, "if it can be final, it should be final."
Testing:
You won't need reflection to set the dependencies. Yes, many mocking frameworks handle this for you, but with constructor injection, you have the option to call new on the constructor.
Nasty NullPointerExceptions:
An object is created by calling its constructor, right? We usually want our arguments to be non-null at the time they are passed in. With constructor injection, the Spring IoC container makes sure that all the arguments passed in the constructor are available before passing them into the constructor.
use constructor injection, Spring also recommends it
In your main code, you should use method 2 as field injection (method 1) is not recommended. (see here for reasons)
In your test code, it's okay to use method 1.
I suggest you suggest something better. By using the Lombok library's #RequiredArgConstructor you are thus avoiding the boilerplate code. and if you wonder why #Autowired not reccomended , because of when you want to write unit testing in your application and there will be problem , where if you use #Autowired.
In addition to what the other answers have said about immutability, another benefit of constructor injection is to be able to avoid NPE is the field is not initialized. Using autowired, from a test, you’d create the class and then must remember to set the field. Using constructor injection, you can’t not initialize the field. This is more prominent in Kotlin where autowired fields are declared as lateinit var and throw a runtime exception if used before initialized. But a constructor argument can be declared as not null type which prevents you from even explicitly passing null.

Methods of Autowiring in Spring - Difference between the two possible alternatives below

I have a basic Auto-wiring Question. I see the following two implementations that are possible in Spring auto-wiring
Method1
public class SimpleMovieLister {
private MovieFinder movieFinder;
#Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
Method2
public class SimpleMovieLister {
#Autowired
private MovieFinder movieFinder;
}
My understanding is that both are the same and I use a lot of Method2 in my code. What are the situations in which Method1 is useful ? Or is it just a case of Spring evolution and we have both possible ways in which to implement.
Sorry, if the question is too basic, but I need to get this cleared up
Method 1 is Setter Injection.
Method 2 is Field Injection.
A 3rd method is Constructor Injection
Example:
public class SimpleMovieLister {
private MovieFinder movieFinder;
#Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
Method 3, Constructor Injection is preferred because it makes testing significantly easier since you can pass in the required dependency.
Also, if your Bean only has 1 Constructor, then you can omit the #Autowired annotation. Spring will automatically choose that constructor method when creating the bean.
A good snippet from the docs:
The Spring team generally advocates constructor injection as it
enables one to implement application components as immutable objects
and to ensure that required dependencies are not null. Furthermore
constructor-injected components are always returned to client
(calling) code in a fully initialized state. As a side note, a large
number of constructor arguments is a bad code smell, implying that the
class likely has too many responsibilities and should be refactored to
better address proper separation of concerns.
Setter injection should primarily only be used for optional
dependencies that can be assigned reasonable default values within the
class. Otherwise, not-null checks must be performed everywhere the
code uses the dependency. One benefit of setter injection is that
setter methods make objects of that class amenable to reconfiguration
or re-injection later. Management through JMX MBeans is therefore a
compelling use case for setter injection.
Use the DI style that makes the most sense for a particular class.
Sometimes, when dealing with third-party classes for which you do not
have the source, the choice is made for you. For example, if a
third-party class does not expose any setter methods, then constructor
injection may be the only available form of DI.
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
Method 1 is setter Injection
Setter injection should primarily only be used for optional
dependencies that can be assigned reasonable default values within the
class. Otherwise, not-null checks must be performed everywhere the
code uses the dependency. One benefit of setter injection is that
setter methods make objects of that class amenable to reconfiguration
or re-injection later.
Method 2 is field Injection

Is #Autowired annotation used correctly?

I use #Autowired annotation like this:
#Autowired
private MyService1 myService1;
#Autowired
private MyService2 myService2;
But new Intellij IDE 2016(3) suggests and proposes to replace:
private final MyService1 myService1;
private final MyService2 myService2;;
#Autowired
public MyClass(MyService1 myService1, MyService2 myService2) {
this.myService1= myService1;
this.myService2= myService2;
}
Tell me what is the difference and what is right?
Both approaches are correct.
From docs
Spring included, provide a mechanism for ensuring that all dependencies are defined when you use Setter Injection, but by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner"
#Autowire at constructor level guarantees that you will have all the required dependencies when your spring container finally creates your bean for that class.
It is suggecting to using constructor inject instead of Setter inject. For nomal use, there is no big different.
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Here is an article to explain it Setter injection versus constructor injection and the use of #Required
Also you can get quite a lot question/answer in stackoverflow.
Setter DI vs. Constructor DI in Spring?
Yes, it is used correctly. This is called the Constructor Injection.
Constructor Injection allows you to use the final modifiers of your choice and to easily pass your own not managed by Spring objects (mocks, for example).
If you are not forced to using field injection, choose constructor injection.

Bean Validation for POST requisition in JAX-RS with Jersey implementation

I'm using the Jersey implementation for JAX-RS, and I was looking for an example where I can use the Bean Validation in POST requisitions. I have this operation, for example:
#POST
#Path("document/annotations/save")
#Produces("application/json")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Map<String, Object> saveAnnotation(
#FormParam("user") String userStr,
#FormParam("documentId") String documentId,
#FormParam("documentPage") Integer documentPage,
#FormParam("annotationContent") String annotationContent,
#FormParam("annotationId") Long annotationId,
#FormParam("isMobile") Boolean isMobile) { // the code... }
I wanna use validations constraints (#NotNull, #Pattern, etc) for each method param. I saw this doc where they're using the Seam Framework to do that.
Currently, I'm trying to use the javax.validation implementation to validate my requests, but it doesn't working.
Is there a way to use the JSR-303 specification with JAX-RS?
Tnks.
This is currently not possible using Jersey; one possible alternative is to write a customer resource filter and bind to the #NotNull, etc. annotations.
It would be simpler if it was encapsulated in a resource class because you could then bind to a #Valid annotation on your method and validate the bean in one shot.
Because JSR-303 is designed to deal with beans and not a collection of parameters then it ends up being very verbose when you try to bend it to your will.
IMHO it's better not to keep validation inside your class anyway and to either use the pipes and filters pattern, i.e. ContainerRequestFilter, or to use something like AspectJ as #Willy suggested.
It's possible. See docs for latest Jersey
https://jersey.java.net/documentation/latest/bean-validation.html#d0e9380
https://jersey.java.net/documentation/latest/bean-validation.html

Handling of pre-slash in #RequestMapping

Imagine that I have a Spring MVC controller something like this:
#Controller
#RequestMapping("/base-url")
public class MyController{
//..snip
#RequestMapping(method=RequestMethod.GET, value="/edit/{id}")
public String edit(Model model, HttpServletRequest request, Authentication authentication){
//..snip
}
}
My question is regarding the inner value parameter to the #RequestMapping annotation at the function level. Is the pre-slash on /edit/{id} required, or does edit/{id} do the job just as well? I would have imagined that the pre-slash would set the request to be absolute, regardless of the class level mapping, but it seems to be ignored.
Is one or the other considered better practice?
In the Spring documentation, they seem to always use the pre-slash. Are there any practical benefits to doing that?
Thanks,
idb.
According to the spring documentation, having a class level #RequestMapping annotation implies that all method level #RequestMappings will be relative to that of the class'.
It might be nice however, to have the ability to override the relative mappings in some rare cases.
I personally prefer to add pre-slash in value of #RequestMapping. In code level you can see: If the value does not start with an / then Spring (DefaultAnnotationHandlerMapping) will add it. Details answer you can visit: Use or not leading slash in value for #RequestMapping. Need official docs or point to Spring source?

Resources