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/
Related
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
Does anyone have any strategies or examples of cross-framework libraries?
I am working on a project with an android app, a java server and a Java desktop client, which all use different frameworks. I need to refactor some core business logic into a separate library that can be used across all of these to ensure consistent behavior, but the field annotations are killing me.
The problem is that I am using Room in the Android app (which requires the #PrimaryKey annotation on the primary key field of a database entity) and JPA in the server and JavaFX client (which requires #Id).
Given this level of difficulty with the models, we initially copy-pasted the fields without annotations to the others when changing them. However, the business logic needs to make use of the models and accommodate each platform's specific ORM, Http client and Json serializer. (I know that it is technically possible to get Gson, Apache Http and Hibernate to run on all of these platforms, but actually doing any of these solutions created too many nightmares of its own)
As far as I can tell, there isn't a nice solution to this. Fortunately, the same #Inject is used in Dagger2 and CDI/CDI-SE so I have created some interfaces that each platform/framework will implement.
Does anybody have any examples or case studies I could look at which might help me arrive at a solution?
(I realize this question doesn't include any code samples, but it's more of a general programming strategy question.)
Disclaimer: I am the architect of JDX for Java and JDXA for Android ORMs.
You may consider using JDX for Java and JDXA for Android ORM frameworks to share the common object model, the core business logic code, and the data integration code across Java server, Java desktop, and Android platforms.
JDX and JDXA don't use annotations to define the mapping - instead they use an external text file to define the mapping specification based on a simple ORM grammar. So you may use the same mapping specification for your common object model across different platforms. Also, the APIs for both JDX and JDXA are simliar.
So, you just need to use the appropriate JDX(A) ORM library for your target platform and an appropriate JDBC driver for your target database without needing to change your object model or business logic.
I am new to Spring and Hibernate. I am actually facing problems defining the layers of my application which is to create a movie site where one can search movies,theaters,search movies by theater names and theaters by movie name.I summing up my queries as follows :-
What could be the entities in my application, I have created MovieEntity and TheaterEntity so far, how to proceed with the mappings between two.
My project structure should be something like this:
Entities, repositories and services. I am not sure where to fit my service layer, as all the methods I need to implement are defined in entities.
Thanks in advance .
There are many ways to do this, and therefore you will not find one definitive answer to your question. (I didn't downvote you, but I suspect that this is the reason for it.)
I would recommend looking at various open source projects (check github) and see how this is done by convention.
One popular way is to create DAO interfaces as a point of access to your data layer and create implementations of those DAOs that are specific to Hibernate. Your services would contain business logic and can use Spring autowiring to link to these interfaces. Your controllers shouldn't contain business logic and should really just route requests. Keep your validation code separate whenever possible too. Doing so makes it particularly easy to unit test.
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.