I am trying to implement applicationContextAware in my servlet.I have the data from client side coming to my servlet.From my servlet I need to pass it to the beans which has getters and setters.I have my DAO s where I have MYSQL operations.
My applicationContext.xml has
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/bazaar_admin_portal" />
<property name="username" value="usrnm" />
<property name="password" value="pwd" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0">
<ref bean="dataSource" />
</constructor-arg>
</bean>
<bean
class="org.dao.impl.TestDAOimpl"
id="TestDAO">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
My web.xml contains
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<description></description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.controllers.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/Test</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
And in my TestServlet under doPost method
private static ApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
applicationContext = ctx;
I have getters and setters class Test.Also interface TestDAO and TestDAOimpl class which implements the interface.
I want to know how do I pass the data from my servlet to the spring side...i.e set the data which will enable the TestDAOimpl to insert into my DB.
Thanks
Are you sure you don't want to use Spring WebMVC? It will handle your problem automatically.
Then try this in you POST Method (It's quite slow, init it lazily):
applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
ApplicationContextAware is for beans to be aware of their application context . Read here for more info . What you could so is use WebApplicationContextUtils WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc) , get the application context , use getBean method and invoke the Dao.
in your servlet
#Autowired
private ApplicationContext ctx;
#Autowired
private MyDao myDao;
#Override
public void init() throws ServletException {
WebApplicationContextUtils.getWebApplicationContext(super.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
}
Related
First of all I have have generic http servlet which I want to run in specific contexts depending on URL mapping (so I switched to HttpRequestHandler implementation). Please consider simplified example. In web.xml I have following configuration:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>testServlet1</servlet-name>
<servlet-class>local.TestServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>testServlet2</servlet-name>
<servlet-class>local.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet1</servlet-name>
<url-pattern>/test1/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>testServlet2</servlet-name>
<url-pattern>/test2/*</url-pattern>
</servlet-mapping>
My servlet is implementation of HttpRequestHandler and looks like here:
public class TestRequestHandler implements HttpRequestHandler {
private Counter counter;
public void setCounter(Counter counter) {
this.counter = counter;
}
#Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.write("<h1>Hello World</h1>");
writer.write("<h1>" + counter.getName() + ": " + counter.getValue() + "</h1>");
}
}
So I want to init both servlet beans (testServlet1 and testServlet2) with different Counters beans and have one root context(applicationContext.xml) for common beans and two separate servlet contexts that could extend and override root context (testServlet1-servlet.xml and testServlet2-servlet.xml). So configuration should be something like this:
<bean id="counter" class="local.Counter">
<property name="name" value="CounterA"/>
</bean>
<bean id="testServlet1" class="local.TestRequestHandler">
<property name="counter" ref="counter"/>
</bean>
and
<bean id="counter" class="local.Counter">
<property name="name" value="CounterB"/>
</bean>
<bean id="testServlet2" class="local.TestRequestHandler">
<property name="counter" ref="counter"/>
</bean>
Is it possible and how could such configuration be implemented? I thought about DispatcherServlet but don't understand how it could be configured with implementation of HttpRequestHandler.
I have found a solution to my task. In few words - We create two DispatcherServlets and each servlet configuration has its own context which extends the root context. Here is the configuration:
web.xml - setup for two DispatcherServlets
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcher2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher1</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher2</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
applicationContext.xml - root context and common beans goes here
<bean id="counter" class="local.Counter">
<property name="name" value="CounterC"/>
</bean>
dispatcher1-servlet.xml - overrides implementation of common beans and specific configuration in own context
<bean id="counter" class="local.Counter">
<property name="name" value="CounterA"/>
</bean>
<bean name="testServlet" class="local.TestRequestHandler">
<property name="counter" ref="counter"/>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/test1">testServlet</prop>
</props>
</property>
</bean>
I tried to find some explanation for what really happens when we do not register ContextLoaderListener in our web.xml file, mainly because I have a simple Spring + Hibernate app that works fine if I DO NOT declare ContextLoaderListener. When I do, I get 404 error.
web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
applicationContext.xml:
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="org.myfantasticwebsite"/>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/pizzashop"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>org.myfantasticwebsite</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
I also have index.jsp that just displays some stuff from database. All 3 files (web.xml, applicationContext.xml and index.jsp) are located in WEB-INF directory, and everything works fine until I add ContextLoaderListener bean to web.xml. After, I get Page not found error on address localhost:8080/pizzashop.
This is just a simple tutorial I found on internet, that's why all configuration is in one file. I was actually trying make separate config files - 2 files stemming from web.xml (dispatcher-servlet.xml with web related config and applicationContext.xml with everything else). Further more to extract hibernate specific config to hibernate.cfg.xml, and spring+hibernate config to hibernate-context.xml.
Can someone please explain why I get 404 error, I'm stuck here for a week now. Thank you.
This is the only controller - PizzaController:
#Controller
#RequestMapping("/")
public class PizzaController {
#Autowired private PizzaDAO pizzaDAO;
/**
* This handler method is invoked when
* http://localhost:8080/pizzashop is requested.
* The method returns view name "index"
* which will be resolved into /WEB-INF/index.jsp.
* See src/main/webapp/WEB-INF/applicationContext.xml
*/
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Pizza> pizzas = pizzaDAO.findAll();
model.addAttribute("pizzas", pizzas);
return "index";
}
}
UPDATE: web.xml with ContextLoaderListener:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
I'm trying to integrate Spring with Vaadin, but I can't use the #Autowired annotation in my Vaadin classes.
Firstly, I created the followed maven structure
This is my web.xml
<web-app>
<display-name>Vaadin Web Application</display-name>
<context-param>
<description>Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class> org.springframework.web.context.request.RequestContextListener </listener-class>
</listener>
<servlet>
<servlet-name>Vaadin Application Servlet</servlet-name>
<servlet-class>com.mycompany.config.AutowiringApplicationServlet</servlet-class>
<init-param>
<description>Vaadin UI to display</description>
<param-name>UI</param-name>
<param-value>com.mycompany.ui.MyUI</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Vaadin Application Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
This is my application-context.xml
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost/vaadin" />
<property name="username" value="postgres" />
<property name="password" value="tobbis" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="persistenceUnitName" value="myUnit"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="com.mycompany.repository"></jpa:repositories>
<context:annotation-config/>
<context:component-scan base-package="com.mycompany" />
Now I created my UserService that is within com.mycompany.services package
#Service
public class UserService {
public void saveUser(User user){
System.out.println("Test to Save");
}
}
And finally, I have my Panel where I want to inject the service
public class UserPanel extends VerticalLayout {
#Autowired
UserService service;
public UserPanel() {
// TODO Auto-generated constructor stub
Injector.inject(this);
service.saveUser();
}
}
but the result is always the same
Error creating bean with name 'com.mycompany.ui.UserPanel': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: com.mycompany.services.UserService com.mycompany.ui.UserPanel.service;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.aiem.services.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Try to declare your UserService at applicationContext.xml
<bean name="userService" class="com.mycompany.services.UserService"></bean>
As far as I know,
Injector.inject(this);
is not something from Spring, you may be mixing it with another framework.
Instead, I would make UserPanel a prototype-scoped Spring component (meaning it can be instantiated and autowired by Spring, but you remain responsible for it's lifecycle).
#Component
#Scope(SCOPE_PROTOTYPE)
public class UserPanel extends VerticalLayout {
Note that a new instance will be created anytime UserPanel is retrieved from the context (e.g. autowired in another object). It could be best to control the creation of instances yourself by explicitly invoking
context.getBean(UserPanel.class)
at the right time.
AnnotationConfigWebApplicationContext is not meant to be used with XML config. It is supposed to be used with the #Configuration annotated classes.
Since you're using an xml file for Spring config, then you should instead remove these lines from web.xml:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
And then by default Spring will use the XmlWebApplicationContext and pick up your xml file.
I have tried the same scenario than you. At the end, the solution is at the Vaadin documentation.
Seems that the problem is that we are using Vaadin context and not Spring context, and therefore we need to do the trick showed in the documentation (SpringHelper) to obtain any bean. Outside of the Spring context, the autowiring is not goint to work.
There is an addon for enabling autowiring via annotations: http://vaadin.xpoft.ru/.
Here is the link to the Vaadin site: http://vaadin.com/addon/springvaadinintegration. Hope it helps.
I am beginner in Web Service and using
Spring 3.0 and spring-webmvc-portlet 3.0
javax.portlet 2.0
I have controller as follows
#Controller(value = "myController")
#RequestMapping(value = "**VIEW**")
public class MyController {
// Controller logic
}
Now, I want to create Web Service using RESTful API in portlet environment.
Please guide me How can i write the Web Service which will return JSON or XML data.
I am still struggling with Web Service not getting WS called.
I am pasting my conf files
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/itemCatalog-portlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>webServiceTest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webServiceTest</servlet-name>
<url-pattern>/myWebService/*</url-pattern>
</servlet-mapping>
item-portlet.xml
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.main.mypackage" />
<bean
class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="myPropertyEditorRegistrar" />
</list>
</property>
</bean>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>content.Language-ext</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="false" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
webServiceTest-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
portlet.xml
itemCatalog
org.springframework.web.portlet.DispatcherPortlet
text/html
view
content.Language-ext
Controller
#Controller
public class WebServiceTest {
#RequestMapping(value = "/myWebService/testing", method = RequestMethod.GET)
public String testMethod() {
return "HELLO WORLD ! SUCCESS";
}
}
I am trying to Hit with
localhost:8080:/myappname/myWebService/testing
Getting no result.
To create Web Service in portlet environment.
1. We need to use org. springframework.web.servlet.DispatcherServlet which is front controller for all the controllers available. All the HTTP request will be dispatched using Dispatcher servlet.
Add an entry in web.xml
<servlet>
<servlet-name>springwebservice</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springwebservice</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Please refer below link for dispatcher servlet read carefully
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
Now importantly each DispatcherServlet must have own WebApplicationContext. WebApplicationContext is nothing but an xml file comprises of controllers,view resolver,beans,etc .
Create file named springwebservice-servlet.xml in WEB-INF. springwebservice-servlet.xml is a WebApplicationContext.
Note
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.
Make sure new WebAppicationContext is created for DispatcherServlet and configure it according to need.
Please guide me if mistaken somewhere.
Quick question based on a spring web app i am creating.
How do you go about setting up the context of the application so that you do not need to set the datasource parameters for simpleJDBC all the time and can call getSimpleJDBCTemplate().queryfor.... and it be set up with the datasource.
This is how i currently have it and it seems to go against inversion of control that spring is meant to provide as this is in every dao!
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
DataSource dataSource = (DataSource) ac.getBean("dataSource");
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
ApplicationContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties.properties"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<bean name="SimpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg><ref bean="dataSource"/></constructor-arg>
</bean>
<context:annotation-config/>
</beans>
Latest Stack Trace from Tomcat log
13-Jan-2011 20:15:18 com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
ptc.jersey.spring
13-Jan-2011 20:15:18 com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class ptc.jersey.spring.resources.LoginResource
13-Jan-2011 20:15:18 com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
13-Jan-2011 20:15:19 com.sun.jersey.spi.spring.container.servlet.SpringServlet getContext
INFO: Using default applicationContext
13-Jan-2011 20:15:19 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.4 09/11/2010 10:30 PM'
13-Jan-2011 20:15:21 com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at ptc.jersey.spring.daoImpl.UserDaoImpl.getUser(UserDaoImpl.java:43)
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>Jersey Spring Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ptc.jersey.spring</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Spring Web Application</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
</web-app>
Any help would be great
Thanks
Chris
Why don't you declare the SimpleJdbcTemplate instance as well in the application context file?
For example with these bean declarations
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="dburl"/>
<property name="username" value="dbusername"/>
<property name="password" value="password"/>
</bean>
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg><ref bean="dataSource"/></constructor-arg>
</bean>
And in your web.xml to load the application context
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
Declare the SimpleJdbcTemplate bean in the context:
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
and use it like this:
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
SimpleJdbcTemplate simpleJdbcTemplate = (SimpleJdbcTemplate) ac.getBean("jdbcTemplate");
or in a DAO:
#Autowired
private SimpleJdbcTemplate simpleJdbcTemplate;
It is thread-safe, and therefore reusable.
What I'd recommend is that you declare your DataSource as bean and also the classes which need it and use dependency injection to introduce the DataSource to your class. As an example, your bean definition could look like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="dataSource" class="...">
<!-- your dataSource config here -->
</bean>
<bean id="yourClassThatNeedsDataSource" class="com.stackoverflow.q4684102.Example">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
and the accompanying class
package com.stackoverflow.q4684102;
import javax.jdbc.DataSource;
import org.springframework.jdbc.core.simple.*;
public class Example implements YourDaoInterface {
private SimpleJdbcOperations jdbc;
public void setDataSource(DataSource ds) {
jdbc = new SimpleJdbcTemplate(ds);
}
// your DAO methods here
}
Why do it this way instead of creating a bean out of the SimpleJdbcTemplate itself?
No difference, really - some people like it the other way, some others like it this way - you wan't have a huge XML with loads of bean definitions for intermediate objects if you do it this way, that's for sure. That, of course, is up to you to decide on how you want to design your software.
If you create SimpleJdbcTemplate inside setDataSource then you are creating a template per Dao instance.
If you configure as a bean and inject into the Dao, then you can resuse the same template across the Daos - which is recommended, because its threadsafe.