Skip to main content
Links:
http://viralpatel.net/blogs/tutorial-spring-3-mvc-introduction-
spring-mvc-framework/
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html
#beans-classpath-scanning
7/20/2012
@entity: The Java Persistence API (JPA) is a POJO persistence API for object/relational
mapping. It contains a full object/relational mapping specification supporting the use of Java
language metadata annotations and/or XML descriptors to define the mapping between Java
objects and a relational database.
Here I’ll present an example of using standard JPA annotations to markup a set of POJOs and
then persist the POJOs by configuring Spring to use the Hibernate
AnnotationSessionFactoryBean. This example does not use the JPA API to work with persisted
objects, rather, JPA annotations are only used to define the ORM mappings. Using these
unaltered POJOs using the JPA API would 100% work and would almost be trivial.
Dependency: To add database connectivity to the siark.com webapp I’m using a MySQL
database To add database connectivity to the siark.com webapp I’m using a MySQL database
and the Hibernate ORM framework. I need to add some dependencies to my pom.xml, some of
which (Hibernate) are not in any of the repositories supported by Nexus in it’s out-of-the-box
state. The Hibernate jar files are available from the JBoss repository.
To add a new proxy repository to Nexus.
1 Log in to Nexus as an admin.
2 Select ‘Proxy Repository’ from the ‘Add’… menu.
3 Enter the ‘Repository ID’ ‘jboss’, ‘Repository Name’ ‘JBoss Repository’, ‘Remote Storage
Location’ ‘http://repository.jboss.org/nexus/content/groups/public’ and press the ‘Save’ button.
4 Select the ‘Public Repositories’ from the repository list. Select the ‘JBoss Repository’ from the
‘Available Repositories’ list and add it to the ‘Ordered Group Repositories’ list. Press the ‘Save’
button.
I can now add Hibernate to my pom.xml.
01 <dependency>
02 <groupId>org.hibernate</groupId>
03 <artifactId>hibernate-core</artifactId>
04 <version>3.5.6-Final</version>
05 </dependency>
06 <dependency>
07 <groupId>org.hibernate</groupId>
08 <artifactId>hibernate-annotations</artifactId>
09 <version>3.5.6-Final</version>
10 </dependency>
For some reason it’s also necessary to add javassist to the pom.xml (A Hibernate dependency
that isn’t included in the dependencies!)
1 <dependency>
2 <groupId>javassist</groupId>
3 <artifactId>javassist</artifactId>
4 <version>3.11.0.GA</version>
5 </dependency>
and slf4j (See http://www.slf4j.org/codes.html#StaticLoggerBinder for more options with slf4j.)
01 <dependency>
02 <groupId>org.slf4j</groupId>
03 <artifactId>slf4j-api</artifactId>
04 <version>1.5.8</version>
05 </dependency>
06 <dependency>
07 <groupId>org.slf4j</groupId>
08 <artifactId>slf4j-simple</artifactId>
09 <version>1.5.8</version>
10 </dependency>
As many of the annotations used in the Hibernate POJO’s are java persistence annotations, it’s
necessary to add persistence-api to the pom.xml.
1 <dependency>
2 <groupId>javax.persistence</groupId>
3 <artifactId>persistence-api</artifactId>
4 <version>1.0</version>
5 </dependency>
As I’m using Spring I also need to add spring-orm.
view source
print?
1 <dependency>
2 <groupId>org.springframework</groupId>
3 <artifactId>spring-orm</artifactId>
4 <version>${org.springframework.version}</version>
5 </dependency>
Note:
A key concept in mavenSW is the idea of a repository. A repository is
essentially a big collection of "artifacts", which are things like jarW, warW, and
earW files. Rather than storing jars within projects (such as in a "lib" directory)
on your machine, jars are stored instead in your local maven repository, and you
reference these jars in this common location rather than within your projects. In
addition, when you build a project into an artifact (typically a jar file), you
usually "install" the artifact into your local maven repository. This enables other
projects to use it.
@Properties
Properties are the last required piece in understanding POM basics. Maven
properties are value placeholder, like properties in Ant. Their values are
accessible anywhere within a POM by using the notation ${X}, where X is the
property.
They come in five different styles:
1. env.X: Prefixing a variable with "env." will return the shell's
environment variable. For example, ${env.PATH} contains the PATH
environment variable.
Note: While environment variables themselves are case-insensitive on
Windows, lookup of properties is case-sensitive. In other words, while
the Windows shell returns the same value for %PATH% and %Path%,
Maven distinguishes between ${env.PATH} and ${env.Path}. As of
Maven 2.1.0, the names of environment variables are normalized to
all upper-case for the sake of reliability.
2. project.x: A dot (.) notated path in the POM will contain the
corresponding element's value. For example:
<project><version>1.0</version></project> is accessible via $
{project.version}.
3. settings.x: A dot (.) notated path in the settings.xml will contain the
corresponding element's value. For example:
<settings><offline>false</offline></settings> is accessible via
${settings.offline}.
4. Java System Properties: All properties accessible via
java.lang.System.getProperties() are available as POM properties,
such as ${java.home}.
5. x: Set within a <properties /> element in the POM. The value of
<properties><someVar>value</someVar></properies> may be used
as ${someVar}.
@Spring stereotype annotations
In above service layer code, we have created an interface ContactService and implemented it
in class ContactServiceImpl. Note that we used few Spring annotations such as @Service,
@Autowired and @Transactional in our code. These annotations are called Spring stereotype
annotations.
The @Service stereotype annotation used to decorate the ContactServiceImpl class is a
specialized form of the @Component annotation. It is appropriate to annotate the service-layer
classes with @Service to facilitate processing by tools or anticipating any future service-specific
capabilities that may be added to this annotation.
@Web.xml
The first step to using Spring MVC is to configure the DispatcherServlet in web.xml. You
typically do this once per web application.
The example below maps all requests that begin with /spring/ to the DispatcherServlet. An
init-param is used to provide the contextConfigLocation. This is the configuration file for
the web application.
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/web-application-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
<load-on-startup>
We can specify the order in which we want to initialize various Servlets.
Like first initialize Servlet1 then Servlet2 and so on.
This is accomplished by specifying a numeric value for the
<load-on-startup> tag.
<load-on-startup> tag specifies that the servlet should be loaded
automatically when the web application is started.
The value is a single positive integer, which specifies the loading
order. Servlets with lower values are loaded before servlets with
higher values (ie: a servlet with a load-on-startup value of 1 or 5 is
loaded before a servlet with a value of 10 or 20).
When loaded, the init() method of the servlet is called. Therefore
this tag provides a good way to do the following:
start any daemon threads, such as a server listening on a TCP/IP port,
or a background maintenance thread
perform initialisation of the application, such as parsing a settings
file which provides data to other servlets/JSPs
If no <load-on-startup> value is specified, the servlet will be loaded
when the container decides it needs to be loaded - typically on it's
first access. This is suitable for servlets that don't need to perform
special initialisation.
@spring-servlet.xml
The spring-servlet.xml file contains different spring mappings such as transaction manager,
hibernate session factory bean, data source etc.
• jspViewResolver bean – This bean defined view resolver for spring mvc. For this bean we
also set prefix as “/WEB-INF/jsp/” and suffix as “.jsp”. Thus spring automatically resolves the JSP
from WEB-INF/jsp folder and assigned suffix .jsp to it.
• messageSource bean – To provide Internationalization to our demo application, we defined
bundle resource property file called messages.properties in classpath.
Related: Internationalization in Spring MVC
• propertyConfigurer bean – This bean is used to load database property file jdbc.properties.
The database connection details are stored in this file which is used in hibernate connection
settings.
• dataSource bean – This is the java datasource used to connect to contact manager
database. We provide jdbc driver class, username, password etc in configuration.
• sessionFactory bean – This is Hibernate configuration where we define different hibernate
settings. hibernate.cfg.xml is set a config file which contains entity class mappings
• transactionManager bean – We use hibernate transaction manager to manage the
transactions of our contact manager application
@Spring Integration
Spring Integration provides an extension of the Spring programming model to support the
well-known Enterprise Integration Patterns. It enables lightweight messaging within Spring-
based applications and supports integration with external systems via declarative adapters.
Those adapters provide a higher-level of abstraction over Spring's support for remoting,
messaging, and scheduling. Spring Integration's primary goal is to provide a simple model
for building enterprise integration solutions while maintaining the separation of concerns
that is essential for producing maintainable, testable code.
@Auto-detecting components
Spring provides the capability of automatically detecting 'stereotyped' classes and
registering corresponding BeanDefinitions with the ApplicationContext. For
example, the following two classes are eligible for such autodetection:
@Service
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
@Using filters to customize scanning
By default, classes annotated with @Component, @Repository, @Service,
or @Controller (or classes annotated with a custom annotation that itself is annotated
with @Component) are the only detected candidate components. However it is simple to
modify and extend this behavior by applying custom filters. These can be added as
either include-filter or exclude-filter sub-elements of the 'component-scan' element.
Each filter element requires the 'type' and 'expression' attributes. Five filtering options
exist as described below.
Table 3.7. Filter Types
Filter Type Example Expression
annotation org.example.SomeAnnotation An annotation to be present at the type lev
Filter Type Example Expression
assignable org.example.SomeClass A class (or interface) that the target compo
aspectj org.example..*Service+ An AspectJ type expression to be matched
regex org.example.Default.*
A regex expression to be matched by the
target components' class names.
custom org.example.MyCustomTypeFilter
A custom implementation of the
org.springframework.core.
type.TypeFilter interface.
Find below an example of the XML configuration for ignoring
all @Repository annotations and using "stub" repositories instead.
<beans ...>
<context:component-scan base-package="org.example">
<context:include-filter type="regex"
expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
@Features of Spring 3.0
• Spring 3.0 framework supports Java 5. It provides annotation based configuration support. Java
5 features such as generics, annotations, varargs etc can be used in Spring.
• A new expression language Spring Expression Language SpEL is being introduced. The Spring
Expression Language can be used while defining the XML and Annotation based bean definition.
• Spring 3.0 framework supports REST web services.
• Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can
now use the @DateFimeFormat(iso=ISO.DATE) and @NumberFormat(style=Style.CURRENCY)
annotations to convert the date and currency formats.
• Spring 3.0 has started support to JPA 2.0.
@J2EE
Java Platform, Enterprise Edition or Java EE is Oracle's enterprise Java computing platform. The
platform provides an API and runtime environment for developing and running enterprise
software, including network and web services, and other large-scale, multi-tiered, scalable,
reliable, and secure network applications. Java EE extends the Java Platform, Standard Edition
(Java SE),[1]
providing an API for object-relational mapping, distributed and multi-tier
architectures, and web services. The platform incorporates a design based largely on modular
components running on an application server. Software for Java EE is primarily developed in the
Java programming language and uses XML for configuration.
@design pattern
http://www.allapplabs.com/java_design_patterns/java_design_patterns.htm
@proxy server configuration
http://onebyteatatime.wordpress.com/2009/04/08/spring-web-service-call-using-proxy-per-
connection/#comment-71
@log4j configuration
http://www.tutorialspoint.com/log4j/index.htm
@Diff Struts And Spring
Difference between struts and springs could be analysed from various facets.
(1) Purpose of each framework.
(2) Various feature offerings at framework level.
(3) The design & stuff.
Firstly, Struts is a sophisticated framework offering the easy 2 develop, structured view/presentation
layer of the MVC applications. Advanced, robust and scalable view framework underpinning reuse and
seperation of concerns to certain extent. Springs is a Lightweight Inversion of Control and Aspect
Oriented Container Framework. Every work in the last sentence carry the true purpose of the Spring
framework. It is just not a framework to integrate / plug in at the presentation layer. It is much more to
that. It is adaptible and easy to run light weight applications, it provides a framework to integrate OR
mapping, JDBC etc., Infact Struts can be used as the presentation tier in Spring.
Secondly, Springs features strictly associate with presentation stuff. It offers Tiles to bring in reuse at
presentation level. It offers Modules allowing the application presentation to segregate into various
modules giving more modularity there by allowing each module to have its own Custom/Default
Request Processor. Spring provides Aspect Oriented programming, it also solves the seperation of
concerns at a much bigger level. It allows the programmer to add the features (transactions, security,
database connectivity components, logging components) etc., at the declaration level. Spring framework
takes the responsibility of supplying the input parameters required for the method contracts at runtime
reducing the coupling between various modules by a method called dependency injection / Inversion of
Control.
Thirdly, Struts is developed with a Front Controller and dispatcher pattern. Where in all the requests go
to the ActionServlet thereby routed to the module specific Request Processor which then loads the
associated Form Beans, perform validations and then handovers the control to the appropriate Action
class with the help of the action mapping specified in Struts-config.xml file. On the other hand, spring
does not route the request in a specific way like this, rather it allows to you to design in your own way
however in allowing to exploit the power of framework, it allows you to use the Aspect Oriented
Programming and Inversion of Control in a great way with great deal of declarative programming with
the XML. Commons framework can be integrated to leverage the validation in spring framework too.
Morethan this, it provides all features like JDBC connectivity, OR Mapping etc., just to develop & run
your applications on the top of this.
@SMTP
http://www.code-crafters.com/abilitymailserver/tutorial_smtp.html
http://www.jroller.com/eyallupu/entry/javamail_sending_embedded_image_in
@nginexNginx is a fast, light-weight web server that can also be used as a load balancer and
caching server. It’s been written to be able to handle an extremely large number of simultaneous
connections in a very efficient manner.
To be able to scale efficiently, nginx does things a bit differently than most web servers. For one,
it doesn’t rely on threads to handle requests. Instead it uses a highly scalable asynchronous
architecture which makes it possible for it to handle thousands of requests at once without using
up a lot of system resources.
Nginx is free and open source, which has made it an easy option for those looking for a small,
high-performance web server. It doesn’t necessarily have to be used on its own, and many sites
use it together with for example Apache for specific tasks.
Nginx was developed by Igor Sysoev for use with one of Russia’s largest sites: Rambler (a web
portal). He started developing the software in 2002, but the first public release wasn’t until 2004.
The popularity of nginx has since exploded and it’s now used by millions of sites.
A few prominent sites that use nginx in one capacity or another are WordPress.com, Hulu, and
SourceForge.
@ virtual machine
A virtual machine (VM) is a software implementation of a computing environment in which an
operating system (OS) or program can be installed and run.
The virtual machine typically emulates a physical computing environment, but requests for CPU,
memory, hard disk, network and other hardware resources are managed by a virtualization layer
which translates these requests to the underlying physical hardware.
VMs are created within a virtualization layer, such as a hypervisor or a virtualization platform
that runs on top of a client or server operating system. This operating system is known as the
host OS. The virtualization layer can be used to create many individual, isolated VM
environments.
02
Virtual machines can provide numerous advantages over the installation of OS's and software
directly on physical hardware. Isolation ensures that applications and services that run within a
VM cannot interfere with the host OS or other VMs. VMs can also be easily moved, copied, and
reassigned between host servers to optimize hardware resource utilization. Administrators can
also take advantage of virtual environments to simply backups, disaster recovery, new
deployments and basic system administration tasks. The use of virtual machines also comes with
several important management considerations, many of which can be addressed through general
systems administration best practices and tools that are designed to managed VMs.
Note: This entry refers to the term virtual machine (VM) as it applies to virtualization
technology which creates independent environments for use by operating systems and
applications which are designed to run directly on server or client hardware. Numerous other
technologies, such as programming languages and environments, also use the same concepts
and also use the term "virtual machine".
@spring 3.0
The Spring framework , created by Rod Johnson, is an extremely powerful Inversion of
control(IoC) framework to help decouple your project components’ dependencies.
New features:
http://www.mkyong.com/tutorials/spring-tutorials/
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html