Apart from coding and design interview questions, this page contains updates on my learnings with Java. It helps me organize my learning. Read about my future self here : https://siliconvalleystories.blogspot.com/
Thursday 31 July 2014
Monday 28 July 2014
Too many open files error java mac
-XX:- MaxFDLimit
Directs the VM to refrain from setting the file descriptor limit to the default maximum. The default behavior is to set the limit to the value specified by
OPEN_MAX
, which is10240
. Normally, this is the maximum number of files that a process may have open. It is possible, however, to increase this limit to a user-specified value with the sysctl
utility. Under such circumstances, you may want to pass -XX:-MaxFDLimit
to stop the Java VM from restricting the number of open files to 10240
.Friday 25 July 2014
Thursday 24 July 2014
Annotations are not supported in source 1.3 maven
Maven compiler plugin uses default JDK1.3 which does not support annotations.
Solution :
<project ....> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
What is lifecycle phase ?
Lifecycle phases are intentionally vague, defined solely as validation, testing, or deployment,
and they may mean different things to different projects. For example, in a project that produces a Java
archive, the package phase produces a JAR; in a project that produces a web application, the package
phase produces a WAR.
Plugin goals can be attached to a lifecycle phase. As Maven moves through the phases in a lifecycle, it will execute the goals attached to each particular phase.
Plugin goals can be attached to a lifecycle phase. As Maven moves through the phases in a lifecycle, it will execute the goals attached to each particular phase.
What are maven goals ?
Goals define parameters that can define sensible default values.
In the archetype:generate exam- ple, we did not specify what kind of archetype the goal was to create on our command line; we simply passed in a groupId and an artifactId. Not passing in the type of artifact we wanted to create caused the generate goal to prompt us for input, the generate goal stopped and asked us to choose an archetype from a list. If you had run the archetype:create goal instead, Maven would have as- sumed that you wanted to generate a new project using the default maven-archetype-quickstart archetype. This is our first brush with convention over configuration. The convention, or default, for the create goal is to create a simple project called Quickstart. The create goal defines a configuration property archetypeArtifactId that has a default value of maven-archetype-quickstart. The Quickstart archetype generates a minimal project shell that contains a POM and a single class.
The Archetype plugin is far more powerful than this first example suggests, but it is a great way to get new projects started fast. Later in this book, we’ll show you how the Archetype plugin can be used to generate more complex projects such as web applications, and how you can use the Archetype plugin to define your own set of projects.
In the archetype:generate exam- ple, we did not specify what kind of archetype the goal was to create on our command line; we simply passed in a groupId and an artifactId. Not passing in the type of artifact we wanted to create caused the generate goal to prompt us for input, the generate goal stopped and asked us to choose an archetype from a list. If you had run the archetype:create goal instead, Maven would have as- sumed that you wanted to generate a new project using the default maven-archetype-quickstart archetype. This is our first brush with convention over configuration. The convention, or default, for the create goal is to create a simple project called Quickstart. The create goal defines a configuration property archetypeArtifactId that has a default value of maven-archetype-quickstart. The Quickstart archetype generates a minimal project shell that contains a POM and a single class.
The Archetype plugin is far more powerful than this first example suggests, but it is a great way to get new projects started fast. Later in this book, we’ll show you how the Archetype plugin can be used to generate more complex projects such as web applications, and how you can use the Archetype plugin to define your own set of projects.
What is a maven plugin ?
To execute a single Maven plugin goal, we used the syntax mvn archetype:generate, where
archetype is the identifier of a plugin and generate is the identifier of a goal.
The core of Maven has little to do with the specific tasks involved in your project’s build. By itself, Maven
doesn’t know how to compile your code or even how to make a JAR file. It delegates all of this work to
Maven plugins like the Compiler plugin and the Jar plugin, which are downloaded on an as-needed basis
and periodically updated from the central Maven repository. When you download Maven, you are getting
the core of Maven, which consists of a very basic shell that knows only how to parse the command line,
manage a classpath, parse a POM file, and download Maven plugins as needed. By keeping the Compiler
plugin separate from Maven’s core and providing for an update mechanism, Maven makes it easier for
users to have access to the latest options in the compiler. In this way, Maven plugins allow for universal
reusability of common build logic. You are not defining the compile task in a build file; you are using
a Compiler plugin that is shared by every user of Maven. If there is an improvement to the Compiler
plugin, every project that uses Maven can immediately benefit from this change. (And, if you don’t like
the Compiler plugin, you can override it with your own implementation.)
What is archetype or How can you create a maven project ?
mvn archetype:generate -DgroupId=org.sonatype.mavenbook \ -DartifactId=simple \ -Dpackage=org.sonatype.mavenbook \ -Dversion=1.0-SNAPSHOT
An archetype is defined as “an original model or type after which other similar things are patterned; a prototype.” A number of archetypes are available in Maven for anything from a simple application to a complex web application, and the archetype:generate offers a list of archetypes to choose from. The plugin is the prefix archetype, and the goal is generate.
The Maven Archetype plugin creates a directory simple/ that matches the artifactId. This is every Maven project has what is known as a Project Object Model (POM) in a file named pom.xml. This file describes the project, configures plugins, and declares dependencies. Our project’s source code and resources are placed under src/main. In the case of our simple Java project this will consist of a few Java classes and some properties file. In another project, this
could be the document root of a web application or configuration files for an application server.
src/main/java and classpath resources are placed inIn a Java project, Java classes are placed insrc/main/resources.TestNG tests are placed in src/test/java, and classpath resources for tests are located in src/test/re-
Our project’s test cases are located in src/test. Under this directory, Java classes such as JUnit orsources.
How to compare maven and ant ?
Apache Ant
-
Ant doesn’t have formal conventions like a common project directory structure or default behav-
ior. You have to tell Ant exactly where to find the source and where to put the output. Informal
conventions have emerged over time, but they haven’t been codified into the product.
-
Ant is procedural. You have to tell Ant exactly what to do and when to do it. You have to tell it
to compile, then copy, then compress.
-
Ant doesn’t have a lifecycle. You have to define goals and goal dependencies. You have to attach
a sequence of tasks to each goal manually.
Apache Maven
-
Mavenhasconventions.Itknowswhereyoursourcecodeisbecauseyoufollowedtheconvention.
Maven’s Compiler plugin put the bytecode in target/classes, and it produces a JAR file in target.
-
Maven is declarative. All you had to do was create a pom.xml file and put your source in the
default directory. Maven took care of the rest.
-
Maven has a lifecycle which was invoked when you executed mvn install. This command
told Maven to execute a series of sequential lifecycle phases until it reached the install lifecycle
phase. As a side-effect of this journey through the lifecycle, Maven executed a number of default
plugin goals which did things like compile and create a JAR.
-
Maven has built-in intelligence about common project tasks in the form of Maven plugins. If you wanted
to write and execute unit tests, all you would need to do is write the tests, place them in ${basedir}/src/test/java, addatest-scopeddependencyoneitherTestNGorJUnit,andrunmvn test.Ifyouwantedtodeploya web application and not a JAR, all you would need to do is change your project type to war and put your docroot in ${basedir}/src/main/webapp. Sure, you can do all of this with Ant, but you will be writing
the instructions from scratch. In Ant, you would first have to figure out where the JUnit JAR file should
be. Then you would have to create a classpath that includes the JUnit JAR file. Then you would tell
Ant where it should look for test source code, write a goal that compiles the test source to bytecode, and execute the unit tests with JUnit.
Without supporting technologies like antlibs and Ivy (even with these supporting technologies), Ant has
the feeling of a custom procedural build. An efficient set of Maven POMs in a project which adheres
to Maven’s assumed conventions has surprisingly little XML compared to the Ant alternative. Another
benefit of Maven is the reliance on widely-shared Maven plugins. Everyone uses the Maven Surefire
plugin for unit testing, and if someone adds support for a new unit testing framework, you can gain new
capabilities in your own build by just incrementing the version of a particular Maven plugin in your
project’s POM.
The decision to use Maven or Ant isn’t a binary one, and Ant still has a place in a complex build. If your current build contains some highly customized process, or if you’ve written some Ant scripts to complete a specific process in a specific way that cannot be adapted to the Maven standards, you can still use these scripts with Maven. Ant is made available as a core Maven plugin. Custom Maven plugins can be implemented in Ant, and Maven projects can be configured to execute Ant scripts within the Maven project lifecycle.
The decision to use Maven or Ant isn’t a binary one, and Ant still has a place in a complex build. If your current build contains some highly customized process, or if you’ve written some Ant scripts to complete a specific process in a specific way that cannot be adapted to the Maven standards, you can still use these scripts with Maven. Ant is made available as a core Maven plugin. Custom Maven plugins can be implemented in Ant, and Maven projects can be configured to execute Ant scripts within the Maven project lifecycle.
How do we add the jars to the class path ussing maven ?
http://maven.apache.org/plugins/maven-dependency-plugin/
http://stackoverflow.com/questions/4687609/maven-not-setting-classpath-for-dependencies-properly
http://maven.apache.org/plugins/maven-dependency-plugin/
http://stackoverflow.com/questions/4687609/maven-not-setting-classpath-for-dependencies-properly
http://maven.apache.org/plugins/maven-dependency-plugin/
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>/User/sayghosh/code/CCMatching/lib/</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix></classpathPrefix>
<mainClass><com.sd.sd.sd></mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
What is M2_REPO and what does mvn:eclipse eclipse do ?
First step is to be able to create a pom.xml, then you have to be able to get mvn:compile and mvn:package running. After that comes your eclipse repo the dev environment, in this page you get that running. Next how do you add jars to the classpath to get the jar running.
- M2_REPO is a variable that defines where maven 2 repository is on your disk
- This means: add definition of M2_REPO to XML file that defines the eclipse workspace
- You can do the same manually if you want. That is what I personally did. Just go to Window/Preferences and then choose Java/Build Path/Classpath Variables. Once you did it you can enjoy maven integration with eclipse. Every time you add new dependency to your pom.xml, runmvn eclipse:eclipse
and refresh you workspace you get all new libraries into classpath of your project.
If you have a simple java project which is made up of only one module, using eclipse is very simple. To generate the eclipse project files from your POM you execute the following command:
mvn eclipse:eclipse
If you have created or checked out the project with eclipse, you only have to refresh the project in your workspace. Otherwise you have to import the project into your eclipse workspace (From the menu bar, select File >Import >Existing Projects into Workspace). In the latter case the project (directory) should not be located in your workspace, because eclipse might come into trouble, especially if you want to use eclipse as the scm client.
http://maven.apache.org/guides/mini/guide-ide-eclipse.html
No projects found to import error in eclipse
http://stackoverflow.com/questions/2638016/why-no-projects-found-to-import
Wednesday 23 July 2014
How would you change your git repository when your location on the server has changed ?
Introduction :
- What is remote ? Remote repositories are versions of your project that are hosted on the Internet or network somewhere
- What is origin ? If you’ve cloned your repository, you should at least see origin — that is the default name Git gives to the server you cloned from
- What does git remote do ? To see which remote servers you have configured, you can run the
git remote
command. It lists the shortnames of each remote handle you’ve specified.
How to :
- git remote rm origin //this will remove the previous origin
- git remote add origin <new url location> //this will add the new location on github as the remote
References :
Tuesday 22 July 2014
Must have eclipse pluggins for Java
- Java source attacher : This pluggin allows you to search the source file and attach it to the jar file. Link Download URL
- Reference : http://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse
- sd
- sd
Appender hasnt been setup so log4j hasnt been properly initialized
- The problem is that the log4j.properties file isn't included in the classpath (it's in the same folder as your Eclipse build path, but Eclipse doesn't have it in its “runtime classpath”.
- To add the log4j.properties file to the Eclipse classpath, click on the Run menu and select the Run Configurations option. Select the Classpath tab. Left-click on the “User Entries” item and then select the Advanced … option. Click the Add External Folder option and then click OK button. Navigate to the folder where you unzipped the crawler4j-x.x zip file and select it.
- https://code.google.com/p/crawler4j/wiki/StepByStepTutorial
Friday 18 July 2014
PATH and CLASSPATH variables
The
The
PATH
variable is generally used to make a command available on the terminal, without having to prepend the full path to call it; basically we will be able to call the Java interpreter from within every folder.The
CLASSPATH
variable is needed to load the core Java libraries instead and makes them available to Solr components. Thursday 17 July 2014
Spring Annotations vs XML
Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.
However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.
I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it.
In general: If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.
http://stackoverflow.com/questions/182393/xml-configuration-versus-annotation-based-configuration |
What is a POJO ?
Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.
class A {}
class B extends/implements C {}
class B extends/implements C {}
Note: B is non POJO when C is kind of distributed framework class or ifc. e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn and not serializable/comparable. Since serializable/comparable are valid for POJO.
Here A is simple object which is independent. B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.
Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.
So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.
JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks. It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.
Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.
Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.
Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.
In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model. Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:
Advantages:
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
Difference between java bean , pojo, vo , dto ?
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
Difference between java bean , pojo, vo , dto ?
JavaBeans
A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:
JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.The required conventions are:
- The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
- The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
- The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.
Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.
POJO
A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any
javax.ejb
interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.
Value Object
A Value Object or VO is an object such as
java.lang.Integer
that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.
Data Transfer Object
Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.
So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.
http://stackoverflow.com/questions/1612334/difference-between-dto-vo-pojo-javabeans
JavaBeans
At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. For example, classes that
- Have a public default (no argument) constructor
- allows access to properties using accessor (getter and setter) methods
- Implement java.io.Serializable
More accurately, JavaBeans are classes that adhere to Sun’s JavaBeans spec, first published way back in 1996. A JavaBean was defined as a “software component model” for Java. The idea was that JavaBeans would be reusable software components that could be manipulated visually in a builder tool and that vendors would create and sell JavaBeans that could be composed together into applications by end users. The three most important features of a Java Bean are
- the set of properties (named attributes) it exposes
- the set of methods it allows other components to call
- the set of events it fires (to notify registered listeners of changes)
POJO
POJO is an acronym for Plain Old Java Object. The term was coined by Martin Fowler et. al., as a ‘fancy’ way to describe ordinary Java Objects that do not require a framework to use, nor need to be run in a application server environment. It is often used to distinguish simpler, lightweight Java objects from ‘heavyweight’ code like EJBs. The use of these kind of lightweight objects in programming is described in books such as “POJOs in Action” and advocated by frameworks like Spring.
Spring beans
A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Frameworkcontainer. Spring beans are defined in a Spring configuration file (or, more recently, by using annotations), instantiated by the Spring container, and then injected into your application.
The reason Spring managed objects are referred to as beans is because in the very early versions, Spring was intended only for use with JavaBeans. That is no longer the case of course: Spring can manage just about any object, even if it doesn’t have JavaBean type characteristics such as default constructors or mutator methods (getters and setters). None the less, the term ‘Spring beans’ has stuck.
Can Spring beans be POJOs? Yes, and they usually are (although they don’t have to be – e.g. Spring can be used with ‘heavyweight’ Java objects, such as EJBs).
Can Spring beans be JavaBeans? As I have said, yes and again they often are but don’t have to be.
Can Spring beans be JavaBeans? As I have said, yes and again they often are but don’t have to be.
Summary
Although it have been well over 10 years since the JavaBeans spec was first published, it still carries weight and has influence the development of modern frameworks such as Spring. But while Java objects that have default constructor and use accessor methods for private fields may legitimately be called JavaBeans, the whole “reusable software component that can be manipulated visually in a builder tool” concept isn’t particularly popular anymore.
POJOs, however, are everywhere and the a backlash against the complexities for EJBs has resulted in widespread use of ‘lightweight’ Java programming.
Spring beans are objects created and managed by the Spring framework.
None of the 3 terms discussed are mutually exclusive. A Java object can be a JavaBean, a POJO and a Spring bean all at the same time.
Spring Annotations
Expanding this into a real system, we might have dozens of such services and components. In each case we can abstract our use of these components by talking to them through an interface (and using an adapter if the component isn't designed with an interface in mind). But if we wish to deploy this system in different ways, we need to use plugins to handle the interaction with these services so we can use different implementations in different deployments.
http://martinfowler.com/articles/injection.html
http://stackoverflow.com/questions/tagged/spring
Unit testing : http://docs.spring.io/spring/docs/2.5.x/reference/index.html
- @RestController - HTTP requests are handled by a controller. These components are easily identified by the
@RestController
annotation.A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller simply populates and returns aGreeting
object. The object data will be written directly to the HTTP response as JSON.This code uses Spring 4’s new@RestController
annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for@Controller
and@ResponseBody
rolled together.TheGreeting
object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’sMappingJackson2HttpMessageConverter
is automatically chosen to convert theGreeting
instance to JSON. - @RequestMapping - The
@RequestMapping
annotation ensures that HTTP requests to/greeting
are mapped to thegreeting()
method. - @RequestParam -
@RequestParam
binds the value of the query string parametername
into thename
parameter of thegreeting()
method. This query string parameter is notrequired
; if it is absent in the request, thedefaultValue
of "World" is used.
Subscribe to:
Posts (Atom)