spring 连接数据库

来源:互联网 发布:淘宝通知买家虚假交易 编辑:程序博客网 时间:2024/06/05 21:04

1.spring配置文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.      xmlns:p="http://www.springframework.org/schema/p"  
  5.      xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="  
  7.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
  9.     ">  
  10.     <!-- bean来定义读取资源文件  
  11.          
  12.     -->  
  13.     <!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  14.         <property name="location" value="classpath:/cn/et/lesson02/jdbc/jdbc.properties"></property>  
  15.     </bean> -->  
  16.     <!--context命名空间 读取资源文件  -->  
  17.     <context:property-placeholder location="classpath:/cn/et/lesson02/jdbc/jdbc.properties"/>  
  18.     <!-- 数据源只是为了获取连接 -->  
  19.     <bean id="dataSouce"  
  20.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  21.         <property name="url" value="${url}"></property>  
  22.         <property name="username" value="${username}"></property>  
  23.         <property name="password" value="${password}"></property>  
  24.         <property name="driverClassName" value="${dirverClass}"></property>  
  25.     </bean>  
  26.     <!-- 封装一些操作的方法 -->  
  27.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  28.         <property name="dataSource" ref="dataSouce"></property>  
  29.     </bean>  
  30. </beans>  

2.使用web连接maven项目

1.在webxml中配置监听
[html] view plain copy
  1. <listener>  
  2.   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  3. </listener>  
2.使用这个对象就可以在serlvet中获取注解对象
[html] view plain copy
  1. ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());  
  2.         GoodsService ns = (GoodsService) ac.getBean("goodsServiceImpl");  

3.在jar项目中获取连接

[html] view plain copy
  1. ApplicationContext context = new GenericXmlApplicationContext("classpath:/cn/et/lesson02/mvc/spring.xml");  
  2. context=(MyController)context.getBean("myController");  
原创粉丝点击