I'm new to Spring and DI in general. But from what I have read, DI affords you the ability to swap out implementations very easily using frameworks like Spring. I can understand value there when it comes to XML bean configuration because code doesn't need to be changed at all for accomplishing switchable implementations. But if we're using annotations like #Autowired or #Qualifier...we would need to change the code. So why do we want to use annotations over XML-based configuration?
This was actually a topic of lively conversation around the time that Spring 3.0 came out in 2009 and JavaConfig was added to the core system base.
In theory, being able to externalize application setup is a great thing. However, it turns out that in practice there are two distinct groups of setup choices: the application shape or dependency graph, and particular values like API keys, database connection strings, and so on that vary between environment but usually don't change the way that the beans are wired.
Experience has shown that the dependency graph, which is essentially what you'd express in XML, is almost never changed without also making changes to the accompanying implementation code anyway, so there is very little real-world benefit to defining the graph in XML. On the other hand, writing #Bean methods in Java means that it's a lot easier to test configuration when needed, the compiler can ensure type safety, and decision logic (such as conditionals) are simpler to implement.
Furthermore, the availability of annotations means that it's possible to extend the domain-specific language for configuration fairly easily in Java--just create a new annotation and its accompanying processor (such as #ConditionalOnProperty); Spring Boot itself is an extreme example of the flexibility of this model. In XML, on the other hand, injecting new tags or attributes into a schema is a lot more of a hassle.
There are times when XML may still be the better choice (I've particularly gone with it for writing out Spring Integration pipelines, which can be easier to read in XML than in the Java DSL), but the real-world benefits turned out not to be all that valuable in most cases, and the safety and flexibility of configuration as code has won out.
This is not must, you have to choices to use Annotations or XML its up to you but Annotations is easy to use, faster and more readable than configurations, and when you use it you will find all the information in a single file, but it also have disadvantages.
Annotations preferable
Use Annotations in anything that is stable and defines the core
structure of the application. Anything that would need a code change
is okay to sit as an annotation.
I recommended you to read the following links for more info :
xml-configuration-versus-annotation-based-configuration
spring-framework-xml-vs-annotations
Related
In my Web-API, i have various methods declared at interface level. And implementation of each method is written at service level. At each method declared i have added audit Annotations, something like this
CreateStackResponse createStack(#AuditId("id") String id, #AuditModule("module") String module, CreateStackRequest createStackRequest)
My Audit table columns are: id, context-id, message, details, user-id, module, submodule,...
How can i build a message(for eg. "create stack request is initiated by abc user") to store. One solution is like at service level i will call one method(say logEvent(required parameters)) which will store audit in database. Can we do this with simple Annotations, at interface level itself?
For example how can i save audit logs as shown in aws elastic beanstalk's event tab.
Annotations do not provide any behavior to your code all by themselves. All that annotations are is what their name implies...extra information attached to your code. The power of annotations comes in when you have code that uses introspection at runtime to look at your compiled code's definitions and do things based on these annotations.
The Spring framework does this extensively. It looks at the annotations on your code and uses them to decide how to wire up your application. It will often create wrapper classes around your own classes so that it can inject its own logic on top of your code.
You could certainly do something like this on your own, but it isn't trivial. I would suggest looking at AspectJ, or some other aspect oriented programming (AOP) framework. I would suggest studying the idea of aspect oriented programming in general, as what you are wanting to do is one of the most common problems that it looks to solve. Using the Spring framework would also be a great leg-up on attacking problems like this. It includes a module for doing AOP, "Spring AOP".
No matter how you go about this with annotations, you're talk about a lot of learning and potentially restructuring your code to use third party packages. You may very well want to give up the idea of using annotations and just put simple logging code in your primary logic.
I just Googled for "using aspect oriented programming for auditing" and got a lot of interesting hits. Here's one such hit. I don't know if it's the best resource for your purpose, but it will give you an idea of what I'm talking about here:
http://idanfridman.com/2014/05/13/clean-auditing-infrastructure-for-your-app-using-aop-custom-annotations-and-reflection/
I'm writing an application with Spring MVC which I'd like to be configurable with properties files. I looked into Spring's util namespace and found this:
<util:properties id="MyProperties" location="propertiesPath" />
with this, I can annotate my classes field simply with
#Value("myProperty")
and have the property simply injected. So, it's very simple to read your properties. But when you have to save them, it's not as intuitive.
I've stumbled upon quite a few questions on how to do it properly and I think this represents best what I want to say: Updating a properties file injected by Spring to include a last run timestamp.
My question is: why it's so difficult to save properties in Spring? Am I doing it the wrong way? At this point I am even wondering if saving properties this way is a good practice or if I should use a database.
From Oracle I can read:
The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.
But Spring seems to make easier only one of them. Please enlighten me.
Thank you.
Spring is largely involved in creating the static, unchanging, structure of your application, and not really involved in transaction processing or business-logic. Often it defines how transactions are to be processed, but it isn't usually involved in the processing itself. We often talk about the separation of the domain model and the architecture -- spring is about architecture.
Writing something out to a store of some kind, say properties to a disk file, is transactional logic (even if you don't need an explicit transaction to do it). It would be one of the end-user features of your system, not part of the architecture -- it would be a feature (even if the end user, in this case, is a sys-admin). Spring has little support for this type of behaviour -- just as it has little support for storing information regarding dynamic changes to the application context.
Using properties like this supposed it read-only. If you need some managing with it, you should better write you custom service with pure java properties handling http://www.mkyong.com/java/java-properties-file-examples/
I'm studying about Java Servlet and I'm curious why Apache Software foundation got rid of web.xml and made the programmers use annotation. Is using annotation better than using web.xml? What are the differences between them?
There is no difference, annotations are just more convenient and prevents you from having bloated web.xml with hundreds of entries (in case of bigger application). It is also a part of Convention over configuration approach. Also note that you don't have to use annotations, you can still register your servlets in web.xml.
There are benefits and drawbacks to using both XML and annotation based Spring configuration files. However, it doesn't have to be an 'either-or' type of decision.
There is a wider issue here, that of XML vs Annotation If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.
If, however, your object model was reused in different applications in such a way that each application wanted to persist the model in different ways, then externalising the meta-data (i.e. XML descriptors) becomes more appropriate.
Neither one is better, and so both are supported, although annotations are more fashionable. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm new to the spring framework. In most of the Spring tutorials I saw, Spring is described as "non-invasive".
What is meant by invasive? What are the merits of using Spring in Java and what makes it non-invasive?
If an IoC container is invasive, it means your code needs to be explicitly aware of dependency injection. For example, in Guice you use the #Inject annotation (and others). These annotations are more standardized than they used to be, which is good - it means with a single set of annotations you can (at least in theory) make your code available for use with various different invasive IoC containers.
With a non-invasive container, you can write your code with no reference to IoC at all... everything is just determined by reflection over members and annotations which would be present even if you weren't using IoC.
There are pros and cons of both invasive and non-invasive containers - being more specific in code can give you more control over some of the details of binding, for example - but it's worth being aware of the difference.
check http://forum.springsource.org/showthread.php?27846-Spring-is-non-invasive
What does it really means?
"You are not forced to import or extend any Spring APIs, example Struts forces you to extend Action".
Of course in some areas, such as the web framework, it's impossible to avoid aplication code depending on the framework. But Spring consistently attempts to reach the non-invasive ideal where configuration management is concerned
Most of the java frameworks force you to extend one of their classes or implement one of their interfaces. Example of such an invasive programming model was EJB 2-era stateless session beans, earlier versions of Struts, WebWork, Tapestry.
Spring avoids littering your code with its API. Spring never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes often don’t have any indication that they’re being used by Spring.
public class HelloWorld {
public String hello() {
return "Hello World";
}
}
This is a simple, Java class(POJO). Nothing indicates that it's a Spring component. Spring is non-invasive means this class could function equally well in a Spring application as it could in a non-Spring application. Although POJOs are simple they can be powerful.
One of the ways POJOs can become powerful in Spring is by using Dependency Injection.
Spring can be invasive and non-invasive, it's only up to you.
Non-invansive spring doesn't use annotations (for example #Autowired) nor its own classes (for example JdbcTemplate), it only uses configuration to wire your beans (simple POJO) together (you still have to initialize spring somehow in your code, which is a little bit invasive anyway). But you are free to drop spring without any significant code changes. Invasive spring, on the other hand, provides you template classes (for persistence, web services,...), annotations and other stuff you cannot simply leave behind without refactoring (if you use them).
EDIT: Some say spring is not invasive, because it doesn't force you to implement interfaces nor extend classes. For me a framework is not invasive, if it can be easily replaced.
An invasive framework means that you are force to extend one of their classes or implement one of their interfaces. You can see that in frameworks like Struts or EJB2. Spring is not-invasive because avoids that. At worst, a class may be annotated with one of Spring's annotation, but it´s otherwise a POJO. So only you need a POJO like that:
package com.habuma.spring;
public class HelloWorldBean {
public String sayHello() {
return "Hello World";
}
}
Spring framework is said to be a non-invasive means it doesn’t force a programmer to extend or implement their class from any predefined class or interface given by Spring API, in struts we used to extend Action Class right that’s why struts is said to be invasive.
In case of struts framework, it will forces the programmer that, the programmer class must extend from the base class provided by struts API.
Use #Resource and #Inject instead of #Component and #Autowired. It is really useful and is standardized across DI frameworks like Spring and Guice.
Invasive meaning - spreading very quickly all around. Spring author says frameworks like EJB, Struts etc are full of framework specific code which is hard to migrate to other frameworks which is against Java philosophy of write once and run anywhere.
Spring says it noninvasive because it uses POJO to write server side so it can be migrated to any platform. But as suggested by at least 2 contributor it in this post, Spring is cancer contrary to what it claims
spring is a cancer to a project that once it has infected your project you can't do anything without hacking at spring config files ... non-invasive is pretty misleading on that front! – user177800 Mar 11 '13 at 7:18
Claiming that Spring is non-invasive is like claiming that the earth is flat. You completely deny reality based on nothing else than your personal bias.
Spring is not only invasive to your code base, it is also invasive to your brain. It will annoy the hell out of you when you have built a decent confidence in searching the web for information and solutions for your programming problems.
I have done serious programming work in some 10 languages and shells, and almost always managed to find useful information, answers and hints to solve my problems. Usually I manage to find convergence towards a decent solution pretty fast, and sometimes after a bit of digging.
Not so with Spring. A once popular scripting language touted the slogan "there's more than way to do it". For Spring, you will mostly find many ways how not to do it, or many ways that will not work in your particular setup.
I do not doubt that Spring has real value. I do see that. But it comes with way too much magic, that works well as long as it works, but once it fails, the tooling and documentation often fail as well.
When I look at Java frameworks like Hibernate, JPA, or Spring, I usually have the possibility to make my configuration via an xml-file or put annotations directly in my classes.
I am cosistently asking myself what way should I go.
When I use annotations, I have the class and its configuration together but with an xml I get a bigger picture of my system because I can see all class-configurations.
Annotations also get compiled in some way I guess and it should be quicker than parsing the xml, but on the other hand, if I want to change my configuration I have to recompile it instead of just changing the xml file (which might become even more handy for production environments on customer side).
So, when looking at my points, I tend to go the xml-way. But when looking at forums or tutorials usually annotations are used.
What are your pros and cons?
A good rule of thumb: anything you can see yourself wanting to change without a full redeploy (e.g. tweaking performance parameters) should really go in something "soft-configurable" such as an XML file. Anything which is never realistically going to change - or only in the sort of situation where you'll be having to change the code anyway - can reasonably be in an annotation.
Ignore any ideas of performance differences between annotations and XML - unless your configuration is absolutely massive the difference will be insignificant.
Concentrate on flexibility and readability.
If you're writing an API, then a word of warning: Annotations can leak out into your public interface which can be unbelievably infuriating.
I'm currently working with APIs where the API vendor has peppered his implementation with Spring MBean annotations, which suddenly means I have a dependency upon the Spring libraries, despite the possibility I might not need to use Spring at all :(
(Of course, if your API was an extension to Spring itself, this might be a valid assumption.)
I think the decision comes down to 'lifecycle', and impedance mismatch between lifecycles.
Lifecycle: Every piece of data, whether its source code, a database row, a compiled class, an object, has a lifecycle associated with it. When does it come into existence and when is it garbage collected?
Suppose I put Hibernate annotations on a Java class. Seems like a reasonable idea, especially if I am creating a new database from scratch and am confident that only this one application will ever connect to it - the lifecycles of my classes, the database schema and the ORM mapping are naturally in sync.
Now suppose I want to use that same class in an API and give it to some third party to consume. The Hibernate annotations leak into my API. This happens because the lifecycle of that class and the database are not the same thing. So we end up using mapping tools to translate between layers of beans in a system.
I try to think about lifecycles and that annotations that can cause lifecycle mismatches should be avoided. Some annotations are relatively harmless in this respect, and some are a hidden danger.
Examples of bad annotations: ORM mapping, database configuration, hard coded config for items that may vary between deployment environments, validations that may vary depending on context.
Examples of harmless annotations: REST endpoint definitions, JSON/XML serialization, validations that always apply.