Ignore S00107 with #JsonCreator annotated constructor - sonarqube

I'm using SQ 6.0 and I have some POJOs which are (de)serialized by Spring/Jackson. For immutability reasons all members are passed to the constructor, so SQ complains with "Constructor has X parameters, which is greater than 7 authorized".
Since the constructor is annotated with #JsonCreator the number of arguments should imho be ignored, is there a way to configure this?

In your case would indeed make sense to have a way to exclude those constructors the same way constructors with #RequestMapping annotation are automatically excluded : https://jira.sonarsource.com/browse/RSPEC-2415. The short answer is no, there is no way. I'm going to open a thread on the SonarQube mailing list on this subject to see what we could do at mid-term.

Related

Spring autowiring based on service availability

I have a need of conditionally creating one of three possible implementations of a service depending upon the environment detected by a Spring application at runtime. If Service A is available, then I want to create a concrete implementation class that uses Service A as a dependency. If Service A is not available, then I want to create an implementation using Service B as a dependency. And so-on.
Classes which depend on the implementation will Autowire the Interface and not care what the underlying Service was that got selected for the particular environment.
My first stab at this was to implement multiple #Bean methods which either return a bean or null, depending on whether the Service is available, and to then have a separate #Configuration class which #Autowire(required=false) the two possible services, conditionally creating the implementation depending on which of the #Autowired fields was not-null.
The problem here is that when required=false, Spring doesn't appear to care whether it waits around for candidates to be constructed; that is to say, the class which tries to pick the implementation might be constructed before one or both of the required=false Beans gets constructed, thus ensuring that one or both might always be null, regardless of whether it may manage to initialize correctly.
It kind of feels like I'm going against the grain at this point, so I'm looking for advice on the "right" way to do this sort of thing, where a whole set of beans might get switched out based on the availability of some outside service or environment.
Profiles don't look like the right answer, because I won't know until after my Service beans try to initialize which implementation I want to choose; I certainly won't know it at the time I create the context.
#Order doesn't achieve the goal either. Nor does #Conditional and testing on the existence of the bean (because it still might not be constructed yet). Same problem with FactoryBean- it does no good to check for the existence of beans that might not have been constructed at the time the FactoryBean is asked to create an instance.
What I really need to do is create a Bean based on the availability of other beans, but only AFTER those beans have at least had a chance to try to initialize.
Spring Profiles is your friend. You can set the current profile by way of environmental variable, command-line argument, and other methods. You can annotate a Spring-managed component so that it's created for a certain profile.
Spring Profiles from the Spring Documentation
Well in this case it turned out to be a tangential mistake that influenced the whole wrong behavior.
To give some background, my first, naive (but workable) approach looked like this:
#Autowired(required=false)
#Qualifier(RedisConfig.HISTORY)
private RLocalCachedMap<String, History> redisHistoryMap;
#Autowired(required=false)
#Qualifier(HazelcastConfig.HISTORY)
private IMap<String, History> hazelcastHistoryMap;
// RequestHistory is an interface
#Bean
public RequestHistory requestHistory() {
if (redisHistoryMap != null) {
return new RedisClusteredHistory(redisHistoryMap);
} else if (hazelcastHistoryMap != null) {
return new HazelcastClusteredHistory(hazelcastHistoryMap);
} else {
return new LocalRequestHistory(); // dumb hashmap
}
}
In other #Configuration classes, if the beans that get #Autowired here aren't available (due to missing configuration, exceptions during initialization, etc), the #Bean methods that create them return null.
The observed behavior was that this #Bean method was getting called after the RLocalCachedMap<> #Bean method got called, but before Spring attempted to create the IMap<> by calling its #Bean method. I had incorrectly thought that this had something to do with required=false but in fact that had nothing to do with it.
What actually happened was I accidentally used the same constant for both #Bean names (and consequently #Qualifiers), so presumably Spring couldn't tell the difference when it was calculating its dependency graph for this #Configuration class... because the two #Autowired beans appeared to be the same thing (because they had the same name).
(There's a secondary reason for using #Qualifier in this case, which I won't go into here, but suffice it to say it's possible to have many maps of the same type.)
Once I qualified the names better, the code did exactly what I wanted it to, albeit in a way that's somewhat inelegant/ugly.
At some point I'll go back and see if it looks more elegant / less ugly and works just as well to use #Conditional and #Primary instead of the if/else foulness.
The lesson here is that if you explicitly name beans, make absolutely sure your names are unique across your application, even if you plan to swap things around like this.

Before vs Around advice precedence in #AspectJ-Style annotations

I have converted a simple Spring project made with pure aop namespace xml coding to the same project but using annotations this time.
I've noticed that now the before-part of the around advice comes out before the before advice, which is the exact opposite behavior of the project's result when I was using aop namespace xml coding.
Is it the default behavior of the annotation style?
See Advice ordering:
When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise the order of execution is undefined. You can control the order of execution by specifying precedence. This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation. Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.
Since the ordering is undefined, it could possibly vary even between multiple executions (having the same xml config).

#XmlSeeAlso Inheritance

First, I am a newbie in the JAXB and Spring world so if I missed something very obvious I would really appreciate it if someone can point it out instead of not replying. :) I tried searching for a solution here but could not find a good answer.
I have a bunch of subclass DTO's(say A1, A2, A3) which inherit from the same abstract class A. I want the result of my rest query to return a list of the subclass type. I have the following class to represent the result
#XmlRootElement(name="result")
#XmlSeeAlso({A1.class, A2.class, A3.class})
public class AResult<T>
{
...
}
Since AResult is generic I would like the #XmlSeeAlso to also be generic and just write something like
#XmlSeeAlso({(subclasses of A.class})
But I do not think that is possible with JAXB from the research I did on this site and elsewhere.
Since we use the annotation-driven tag in the config, it automatically uses the Jaxb2RootElementHttpMessageConverter class. This message converter creates the JaxbContext using the classes defined in #XmlSeeAlso among others. The createMarshaller and getContext methods are immutable in a superclass.
Because of point 1, I can not write a class where I can check if a class is a subclass of class A and then add it to the JaxbContext. I cannot use a custom Jaxb2RootElementHttpMessageConverter or a custom Marshaller.
How do I get around this? BTW, we are using Spring version 3.1.3
Thanks for your help.
JAXB doesn't scan your classpath for classes that might just happen to be subclasses of AResult (that would be rather slow!) but rather relies on the context knowing about all the classes that it might ever have to create instances of. All the #XmlSeeAlso annotation does is extend the context with the additional classes listed.
However, there are a number of other approaches. For example, you could create a class marked with #XmlRegistry that knows how to make the subclasses that you care about. Or you could experiment with using #XmlJavaTypeAdapter. Alas, I've only ever progressed as far as using the #XmlSeeAlso-based approach in my own code, so I can't comment really from experience.

Spring setter injection and constructor injection

Kindly let help to understand in which scenario I should user constructor injection and setter injection. Please help me with appropriate Example.
Thanks in advance.
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).
More details http://blog.springsource.org/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
Personally, I tend towards constructor injection, and I do it for one primary reason.
Immutability.
With immutable objects, it is easier to make code thread safe. This is especially important when dealing with Spring singleton scope objects. If they are mutable, and accessed in different threads, it is not safe to change any of the shared state.
There are other reasons that immutability is beneficial, but I will let a webpage go on about that.

Setter DI vs. Constructor DI in Spring?

Spring has two two types of DI: setter DI and construction DI.
Constructor-based DI fixes the order in which the dependencies need to be injected. Setter based DI does not offer this.
Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time.
I do not see any other significant differences, as both types of Spring DI provide the same features - both setter and constructor DI inject the dependency when the code starts up. Granted, constructor DI will do it through the constructor while setter DI will do it through a setter right after constructing the object, but it does not make any difference for the developer in terms of performance, etc. Both also offer means to specify the order of dependency injection as well.
I'm looking for a scenario where one provides a distinct advantage over the other or where one type is completely unusable.
When it comes to Spring specific pros and cons:
Constructor injection (from the definition) does not allow you to create circular dependencies between beans. This limitation is actually an advantage of constructor injection - Spring can resolve circular dependencies when setter injection is used without you even noticing.
On the other hand if you use constructor injection CGLIB is not able to create a proxy, forcing you to either use interface-based proxies or a dummy no-arg constructor. See: SPR-3150
You should be deciding based on design considerations, not tool (Spring) considerations. Unfortunately, Spring has trained us to use setter injection because when it was originally conceived, there was no such thing as an "annotation" in Java, and in XML, setter injection works and looks much better. Today, we're freed from those constraints, thus allowing it to be a design decision again. Your beans should use constructor injection for any dependencies that are required by the bean and setter injection for dependencies that are optional and have a reasonable default, more or less as OOD has been telling us from the beginning.
Constructor Injection: We are injecting the dependencies through Constructor.
Generally we can use for Mandatory dependencies.
If you use the Constructor injection there is one disadvantage called "Circular Dependency".
Circular Dependency: Assume A and B. A is dependent on B. B is dependent on A. In this constructor injection will be failed. At that time Setter injection is useful.
If Object state is not inconsistent it won't create Object.
Setter Injection: We are injecting the dependencies through Setter methods.
This is useful for Non-Mandatory dependencies.
It is possible to re injecting dependencies by using Setter Injection. It is not possible in Constructor injection.
As per the content from spring.io from Spring 5 onwards
Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the #Required annotation on a setter method can be used to make the property a required dependency.
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.
Here is the link for above quote
But, all of the injections types are available and none of them are deprecated. At a high-level you get the same functionality across all injection types.
In short, choose the injection type that works best for your team and project.
Recommendations from the Spring team and independent blog posts will vary over time. There is no hard-fast rule.
If a particular injection style was not recommended by the Spring team, then they would mark it as deprecated or obsolete. That is not the case with any of the injection styles.
Prefer setter injection.
Think what would be without spring (as Ryan noted). Would you pass the dependencies in constructor? If there are too many dependencies this seems wrong. On the other hand the constructor may be used to enforce the valid state of the object - require all dependencies and verify if they are non-null.
Proxies are another thing (As Tomasz noted) - you will need a dummy constructor which defeats the whole idea.
There is a 3rd option btw - field injection. I tend to be using that, although it is not such a good design decision, because it saves an extra setter, but if this is used outside of spring I will have to add the setter.
My 2 cents.
Assume a classA with 10 fields, with few injected dependencies.
Now if you need entire classA with all fields then you can go for constructor injection.
But if you need only one of the injected field to use in that class you can use setter injection.
This way,
You will not create new object each time.
You do not need to worry about circular dependency issue(BeanCurrentlyInCreationException).
You will not have to create other fields for class A so you have much more flexible code
Since you can mix both, Constructor DI- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Note that the use of a #Required annotation on a setter can be used to make setters required dependencies.
Probably it's not main advantage. But let me explain mechanism of injection in Spring.
The meaning of the difference these two approaches is that with the way of injection using #Inject, #Autowire and so on, Spring will inject one bean into another using reflection, and with the way of the constructor, we ourselves use the constructor in order to initialize one bean by another bean without using reflection.
Therefore, the way with constructor better other option, at least that we don't use reflection-mechanism because reflection is an expensive operation from the machine-side.
P.S. Please consider, that correct use of construction DI it's when you manually create bean through constructor with params, even though you can you create using constructor without any of them.
no, even Constructor Injection happen , injection is still working, but just limited initialize , setter injection is optional and flexible. but it may generally for the parameter class , a spring bean with other spring beans

Resources