前提:已经部署spring(参考上篇:web project 部署 spring bean工厂)
一:新增依赖jar包
1:spring-aop-4.1.6.RELEASE.jar (修改applicationContext.xml中beans属性时需要)
二:web.xml不变,修改applicationContext.xml
1:去掉dtd(<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">)
2:新增beans属性(xmlns,xmlns:xsi,xmlns:context,xsi:schemaLocation)
3:去掉<bean/>的容器注入,修改为注解扫描注入
4:去掉<bean/>之间的关联注入,修改为注解自动注入
三:spring容器类采用注解注入注出
1:注入spring容器(@Component、@Controller、@Service、@Repository)
2:spring容器中注出到bean中(@Resource(name="xxx")、@Autowired)
ps:
1:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <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"> <context:annotation-config /> <!-- 根据注解扫描类放入容器 --> <context:component-scan base-package="dao,service" /> <!--升级: 注解,自动注入 --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> </beans>
2:servlet不变,service(StudentServiceImpl)
package service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import dao.StudentDao; import entity.Student; @Service("studentService") public class StudentServiceImpl implements StudentService { @Resource(name="a") private StudentDao studentDaot; public void insertStudent(Student student){ studentDaot.insert(student); } }
3:dao(StudentDaoImpl)
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import org.springframework.stereotype.Repository; import entity.Student; @Repository("a") public class StudentDaoImpl implements StudentDao { public void insert(Student student){ try{ Class.forName(driver); Connection con = DriverManager.getConnection(url,userName,password); Statement sql = con.createStatement(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sql.execute("insert student(name,math,create_time) values(‘"+student.getName()+"‘,‘"+student.getMath()+"‘,‘"+sdf.format(student.getCreateTime())+"‘)"); sql.close(); con.close(); }catch(java.lang.ClassNotFoundException e){ System.err.println("ClassNotFoundException:" + e.getMessage()); }catch(SQLException ex){ System.err.println("SQLException:" + ex.getMessage()); } } }
时间: 2024-10-25 15:42:58