Spring: Data Sources Configurations
Spring provides several options for making a DataSource available to your application.
1) Getting a DataSource from JNDI
<bean
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
We have now wired in our server's DataSource and its connection pooling facility
2) Creating a DataSource connection pool
<bean id=“myDataSource” class=“com.mchange.v2.c3p0.ComboPooledDataSource” destroy-method=“close”>
<property name=“driverClass” value=“net.sourceforge.jtds.jdbc.Driver” />
<property name=“jdbcUrl” value=“jdbc:jtds:sqlserver://R2DDEV2:1433/sampleDB” />
<property name=“user” value=“sa” />
<property name=“password” value=“dev123″ />
</bean>
We now have a DataSource with connection pooling independent of an application server.
3) Using a DataSource while testing
DriverManagerDataSource. This class can easily be configured and used with a unit test or suite of unit tests.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
You now have a DataSource to use when testing your data access code.
Using JdbcTemplate
JdbcTemplate template = new JdbcTemplate(myDataSource);
All of Spring’s DAO template classes are thread-safe, we only need one
JdbcTemplate instance for each DataSource in our application
<bean id=”jdbcTemplate“
class=”org.springframework.jdbc.core.JdbcTemplate”>
<property name=”dataSource“><ref bean=”dataSource”/></property>
</bean>
<bean id=”studentDao” class=”StudentDaoJdbc”>
<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>
</bean>
<bean id=”courseDao” class=”CourseDaoJdbc”>
<property name=”jdbcTemplate“><ref bean=”jdbcTemplate“/></property>
SPRING: AOP:Advice
Any functionality that exists in an application, but cannot be added in a desirable way is called a cross-cutting concern.
That cross-cutting concern is called aspect-oriented programming (AOP). It deals with the functionality in applications that cannot be efficiently implemented with pure object-oriented techniques.
One of the core features of AOP frameworks is implementing cross-cutting concerns once and reusing them in different places and in different applications. In AOP jargon, the implementation of a cross-cutting concern is called an advice.
AOP frameworks allow you to define which advice is applied to which methods
Spring AOP supports four advice types that each represents a specific scenario for advice implementations:
Around advice: Controls the execution of a join point. This type is ideal for advice that needs to control the execution of the method on the target object.
Before advice: Is executed before the execution of a join point. This type is ideal for advice that needs to performan action before the execution of the method on the target object.
After advice: Is executed after the execution of a join point. This type is ideal for advice that needs to perform an action after the execution of the method on the target object.
Throws advice: Is executed after the execution of a join point if an exception is thrown. This type is ideal for advice that needs to performan action when the execution of the method on the target object has thrown an exception.
JDBC with Spring
Spring JDBC framework will clean up your JDBC code by putting the burden of Resource management and Error handling. This leaves you free to write the statements and queries to get your data to and from the database.
JdbcTemplate template = new JdbcTemplate(myDataSource);
Spring DAO template classes are thread-safe, we only need one JdbcTemplate instance for each DataSource in our application.
<bean id=”jdbcTemplate” class=”org.springframework.jdbc.core.JdbcTemplate“>
<property name=”dataSource”><ref bean=”dataSource“/></property>
</bean>
Writing data
The JdbcTemplate uses several of these callbacks when writing data to the database.
Now whenever the JdbcTempate calls on this class to create a PreparedStatment, it will also be able to log the executed SQL. This can prove invaluable during development and debugging.
Reading data
We simply need to tell Spring what to do with each row in the ResultSet. We do so through the RowCallbackHandler interface by implementing its only method:
void processRow(java.sql.ResultSet rs)
This method is called for each row in our ResultSet.
There is also a sub-interface you can implement that is useful for retrieving multiple objects through a query.
The RowMapper interface is responsible for mapping a ResultSet row to an object.
Suppose we want a method that retrieves all of our objects. To do this we would implement ResultReader.
Spring provides an implementation of this interface that does exactly what we need: RowMapperResultReader. The RowMapper interface is responsible for mapping a ResultSet row to an object.
jdbcTemplate.query(sql, params, rowMapperResultReaderObj);
Query function pull data to create domain objects. But what about queries that just return simple types, like int or String? JdbcTemplate also contains some convenience methods for precisely this.
jdbcTemplate.queryForInt(“select count(*) from Students”);
query()
queryForInt()
queryForObject()
Calling stored Procedures
Spring provides the same support for calling stored procedures as it does for executing statements and queries. This time get the support by implementing CallableStatementCallback.
CallableStatementCallback cb = new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException{
cs.execute();
return null;
}
};
jdbcTemplate.execute(“{ ARCHIVE_Vehicle_Volume_Data }”, cb);
We have all the benefits of resource management and exception handling.All we have to do is define the name of our stored procedure and execute it.
SqlUpdate object
To create a reusable object for executing inserts or updates, you subclass the SqlUpdate class.
MappingSqlQuery
Querying the database with a MappingSqlQuery To model a query as an object, we subclass the MappingSqlQuery class.
Auto-incrementing keys
Spring provides a means to do this via the DataFieldMaxValueIncrementer interface. This interface has three different methods for obtaining the next value to be used as a key: nextIntValue(),
nextLongValue(), and nextStringValue().
BeanFactory
It is an implementation of the “Factory Design Pattern”; It is a class whose responsibility is to CREATE and DISPENSE beans. A bean factory is a general-purpose factory, creating and dispensing many types of beans. It is also able to create associations between collaborating objects as they are instantiated. A bean factory also takes part in the lifecycle of a bean, making calls to custom initialization and destruction methods, if those methods are defined.
There are many implementations of BeanFactory in Spring.
org.springframework.beans.factory.xml.XmlBeanFactory It loads its beans based on the definitions contained in an XML file
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“beans.xml“));
ApplicationContext
An ApplicationContext is much the same as a BeanFactory But an ApplicationContext offers much more:
-> provide a means for resolving text messages.
-> provide a generic way to load file resources.
-> publish events to beans that are registered as listeners.
ApplicationContext are three that are commonly used:
ClassPathXmlApplicationContext—Loads a context definition from an XML file located in the classpath, treating context definition files as classpath resources.
FileSystemXmlApplicationContext—Loads a context definition from an XML file in the file system.
XmlWebApplicationContext—Loads context definitions from an XML file contained within a web application.
ApplicationContext context = new FileSystemXmlApplicationContext(“beans.xml”);
ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);
FileSystemXmlApplicationContext will look for beans.xml in a specific location within the file system, whereas Class PathXmlApplicationContext will look for foo.xml anywhere in the classpath.
A bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. An application context is a bit smarter and preloads all singleton beans upon context startup. By preloading singleton beans, you ensure that they will be ready to use when needed—your application won’t have to wait for them to be created.
Autowiring
Normally in Spring bean’s properties are wired using either the <constructor-arg> or the <property> element.
Spring automatically figure out how to wire beans together by setting the autowire property on each <bean> that you want Spring to autowire.
Spring provides four flavors of autowiring
byName—Attempts to find a bean in the container whose name (or ID) is the same as the name of the property being wired. If a matching bean is not found, the property will remain unwired.
byType—Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired. If more than one bean matches, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.
constructor—Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. In the event of ambiguous beans or ambiguous constructors, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.
autodetect—Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring
Autowiring by default: means beans will not be autowired unless you set the autowire attribute. However, you can set a default autowiring for all beans within the Spring context by setting default-autowire on the root <beans> element:
<beans default-autowire=”byName”> — </beans>
You can also do Mixing auto with explicit wiring.
Spring Bean Scoping
By default, all Spring beans are singletons. To force Spring to produce a new bean instance each time one is needed, you should declare the bean’s scope attribute to be prototype.
Spring: AOP
Aspects are often described in terms of advice, pointcuts, and joinpoints.
Advice: the job of an aspect is called advice; Advice defines both what and the when of an aspect describing the job that an aspect will perform, advice addresses the question of when to perform the job. Before a method or after the method is invoked.
Joinpoint: A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.
Pointcut: pointcuts define the where. A pointcut definition matches one or more joinpoints at which advice should be woven
Aspect: An aspect is the merger of advice and pointcuts
Spring MVC: Handling exceptions
SimpleMappingExceptionResolver
comes to the rescue when an exception is thrown from a controller. Use the following <bean> definition to configure SimpleMappingExceptionResolver to gracefully handle any java.lang.Exceptions thrown from Spring MVC controllers:
<bean id=”exceptionResolver” class=”org.springframework.web.
➥
servlet.handler.SimpleMappingExceptionResolver”>
<property name=”exceptionMappings”>
<props>
<prop key=”java.lang.Exception”>someError</prop>
</props>
</property>
</bean>
The exceptionMappings property takes a java.util.Properties
that contains a mapping of fully qualified exception class names to logical view names.
The base Exception class is mapped to the View whose logical name is someError so that if any errors are thrown, users won’t have to see an ugly stack trace in their browser. When a controller throws an Exception, SimpleMappingExceptionResolver
will resolve it to someError, which in turn will be resolved to a View using whatever view resolver(s) are configured.
Throwaway controllers
Throwaway controllers are significantly simpler than the other controllers, as evidenced by the ThrowawayController interface:
public interface ThrowawayController {
ModelAndView execute() throws Exception;
{
}
}
To create your own throwaway controller, all you must do is implement this interface and place the program logic in the execute() method
Instead of being given parameters through an HttpServletRequest or a command object, throwaway controllers act as their own command object.
The execute() method in throwaway must return a ModelAndView object when it has finished. Just as with any controller, you also must declare throwaway controllers in the DispatcherServlet’s context configuration file.
But the scope attribute has been set to prototype. By default all beans are singletons.
Setting scope to prototype tells Spring to throw the controller away after it has been used and to instantiate a fresh instance for each request.
You must tell DispatcherServlet to use a different handler adapter. Specifically, you must configure ThrowawayControllerHandlerAdapter as follows:
<bean id=”throwawayHandler” class=”org.springframework.web.
➥ servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter”/>
By just declaring this bean, you are telling DispatcherServlet to replace its default handler adapter with ThrowawayControllerHandlerAdapter.
Consequently, you still need DispatcherServlet to use its regular handler adapter as well. Thus, you should also declare SimpleControllerHandlerAdapter as follows:
<bean id=”simpleHandler” class=”org.springframework.web.
➥ servlet.mvc.SimpleControllerHandlerAdapter”/>
Declaring both handler adapters lets you mix both types of controllers in the same application.