SpringIOC
作者:互联网
Spring 是分层的javaSE/EE的全栈式轻量级开源框架
- 全栈式是指对各种主流技术和框架都进行了整合,同时对三层架构提供了解决方案,包括在web层的springmvc service层的spring核心框架完成对事务的控制和对象的管理,dao层的spring jdbcTemplate 完成持久层数据的交互
- 轻量级是指启动时需要加载的资源少,耦合度小,轻量级与重量级的划分依据是使用了多少服务
- spring两大核心:IOC和AOP
- IOC:Inverse Of Control,控制反转,把对象的创建权交给spring
- AOP:Aspect Oriented Programming,面向切面编程,指在不修改源代码的情况下,对方法进行增强
- 优势
- 方便解耦,简化开发,spring是一个容器,将所有对象创建和关系维护交给spring管理,利用IOC进行程序解耦
- AOP编程的支持,方便对程序进行权限拦截等方法的增强
- 声明式事务的支持,通过配置完成事务的管理
- 方便测试,降低javaEE API 的使用,可以使用注解测试
- 方便集成各种优秀框架,内部提供支持
1.自定义IOC容器
package com.rf.service.Impl; import com.rf.dao.Impl.UserDaoImpl; import com.rf.dao.UserDao; import com.rf.service.UserService; import com.rf.utils.BeanFactory; public class UserServiceImpl implements UserService { public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException { //传统方式 // UserDao userDao = new UserDaoImpl(); //反射机制获取,解决了编译期依赖的问题 //UserDao userDao = (UserDao) Class.forName("com.rf.dao.Impl.UserDaoImpl").newInstance(); //出现了硬编码问题,通过配置文件解决 UserDao userDao = (UserDao) BeanFactory.getInstance("userDao"); userDao.save(); } }
package com.rf.utils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.InputStream; import java.util.HashMap; import java.util.List; public class BeanFactory { private static HashMap<String,Object> iocmap=new HashMap<>(); //静态代码块加载 static { //1,获取配置文件 InputStream resource = BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml"); //2.创建SaxReader 对象 SAXReader saxReader = new SAXReader(); //3. 使用dom4j解析文件 try { Document document = saxReader.read(resource); //获取节点 String xpath="//bean"; List<Element> list = document.selectNodes(xpath); for (Element element : list) { String id = element.attributeValue("id"); String classname = element.attributeValue("class"); Object o = Class.forName(classname).newInstance(); iocmap.put(id,o); } } catch (DocumentException | ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } public static Object getInstance(String id){ return iocmap.get(id); } }
<beans> <bean id="userDao" class="com.rf.dao.Impl.UserDaoImpl"></bean> </beans>
2.spring快速入门
- 创建java项目,导入spring开发基本坐标
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
- 编写Dao接口和实现类
public interface UserDao { public void save(); } public class UserDaoImpl implements UserDao { public void save() { System.out.println("dao被调用了....."); } }
- 创建spring核心配置文件
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="com.dao.impl.UserDaoImpl"></bean> </beans>
- 在spring配置文件中配置 UserDaoImpl并使用
@Test public void test01(){ ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml"); UserDao userDao = (UserDao) applicationContext.getBean("userDao"); userDao.save(); }
3. spring API
- BeanFactory是IOC的核心接口,定义了IOC的基本功能,可以读取配置文件,但不会立即生成,当第一次调用getBean方法时创建指定对象的实例
@Test public void test02(){ //通过BeanFactory创建,不会立即创建所有对象实例 BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("ApplicationContext.xml")) ; //当调用getbean方法会创建该对象对应的实例 UserDao userDao = (UserDao) beanFactory.getBean("userDao"); userDao.save(); }
- ApplicationContext 代表应用上下文,spring容器一旦启动,变加载配置文件并立即创建所有对象实例,只初始化一次
- 实现类ClassPathXmlApplicationContext,从类的根路径下加载配置文件 推荐使用这种。
- FileSystemXmlApplicationContext,从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
- AnnotationConfigApplicationContext,当使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。
- 常用方法
- Object getBean(String name);,根据Bean的id从容器中获得Bean实例,返回是Object,需要强转。
- <T> T getBean(Class<T> requiredType);根据类型从容器中匹配Bean实例,当容器中相同类型的Bean有多个时,则此方法会报错。
- <T> T getBean(String name,Class<T> requiredType);根据Bean的id和类型获得Bean实例,解决容器中相同类型Bean有多个情况
@Test public void test01(){ //应用上下文 ,从类路径实现 // ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml"); //磁盘文件实现 ApplicationContext applicationContext = new FileSystemXmlApplicationContext("D:\\学习资料\\java小白学习资料\\java跟课学\\第六阶段\\模块二\\springquickstart\\src\\main\\resources\\ApplicationContext.xml"); //通过字符串获取对象,需要强制转换 // UserDao userDao = (UserDao) applicationContext.getBean("userDao"); //通过泛型获取对象, // <bean id="userDao" class="com.dao.impl.UserDaoImpl"></bean> //<!--当出现多个类型匹配改类型时,对象无法获取--> // <bean id="userDao2" class="com.dao.impl.UserDaoImpl"></bean> UserDao userDao = applicationContext.getBean(UserDao.class); userDao.save(); }
4. Bean
- Bean标签基本配置
- id:Bean实例在Spring容器中的唯一标识
- class:Bean的全限定名,默认情况下它调用的是类中的 无参构造函数,如果没有无参构造函数则不能创建成功
- bean范围标签 scope
- singleton: 只有一个bean实例,生命周期:创建(当应用加载,创建容器时,对象就被创建了 )==》使用(只要容器在,对象一直活着 )==》销毁(当应用卸载,销毁容器时,对象就被销毁了)
- prototype:多例,当调用getBean()方法时实例化Bean,生命周期: 创建(当使用对象时,创建新的对象实例 )==》使用(只要对象在使用中,就一直活着 )==》销毁(当对象长时间不用时,被 Java 的垃圾回收器回收了)
取值范围 |
说明 |
singleton | 默认值,单例的 |
prototype | 多例的 |
request | WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中 |
session | WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中 |
global session |
WEB项目中,应用在Portlet环境,如果没有Portlet环境那么globalSession 相当 于 session |
//singleton 只创建一个实例 UserDao userDao = (UserDao) beanFactory.getBean("userDao");//com.dao.impl.UserDaoImpl@f79e UserDao userDao1 = (UserDao) beanFactory.getBean("userDao");// com.dao.impl.UserDaoImpl@f79e System.out.println(userDao); System.out.println(userDao1); //prototype UserDao userDao2 = (UserDao) beanFactory.getBean("userDao2");//com.dao.impl.UserDaoImpl@7ee8290b UserDao userDao3 = (UserDao) beanFactory.getBean("userDao2");// com.dao.impl.UserDaoImpl@1f59a598 System.out.println(userDao2); System.out.println(userDao3);
- bean实例初始化与销毁
- init-method:指定类中的初始化方法名称
- destroy-method:指定类中销毁方法名称
@Test public void test01() { //磁盘文件实现 FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext("D:\\学习资料\\java小白学习资料\\java跟课学\\第六阶段\\模块二\\springquickstart\\src\\main\\resources\\ApplicationContext.xml"); //通过字符串获取对象,需要强制转换 UserDao userDao = (UserDao) applicationContext.getBean("userDao"); userDao.save(); applicationContext.close(); }
- bean实例化方式
- 无参构造方法实例化
- 工厂静态方法实例化
- 工厂普通方法实例化
<!--方式一 无参方法构造--> <bean id="userDao" class="com.dao.impl.UserDaoImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean> <!--当出现多个类型匹配改类型时,对象无法获取--> <bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype"></bean> <!-- 方式二 静态工厂模式--> <bean id="staticUser" class="com.factory.StaticBeanFactory" factory-method="createUserDao"></bean> <!-- 方式三 普通工厂模式--> <bean id="CommonBeanFactory" class="com.factory.CommonBeanFactory"></bean> <bean id="commonUser" factory-bean="CommonBeanFactory" factory-method="createUserDao"></bean>
5. bean依赖注入
依赖注入 DI(Dependency Injection):它是 Spring 框架核心 IOC 的具体实实现,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。IOC 解耦只是降低他们的依赖关系,但不会消除。需要通过spring框架把持久层对象传入到业务层
- 构造方法注入
<!--构造方法注入--> <bean id="userService" class="com.service.impl.UserServiceImpl"> <!-- <constructor-arg index="0" type="com.dao.UserDao" ref="userDao"/>--> <constructor-arg name="userDao" ref="userDao"></constructor-arg> </bean> private UserDao userDao; public UserServiceImpl(UserDao userDao) { this.userDao = userDao; }
- set注入
- 普通设置
<!-- set 方法--> <bean id="userService" class="com.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> public void setUserDao(UserDao userDao) { this.userDao = userDao; }
-
- p简化注入需要引入p命名空间xmlns:p="http://www.springframework.org/schema/p“
<bean id="userService" class="com.service.impl.UserServiceImpl" p:userDao-ref="userDao"> </bean>
-
- <property>标签:属性注入 name属性:属性名称 value属性:注入的普通属性值 ref属性:注入的对象引用值 <list><set><array><map><props>
- 普通数据类型
<bean id="user" class="com.lagou.domain.User"> <property name="username" value="jack"/> <property name="age" value="18"/> </bean>
- 引用数据类型
<bean id="userService" class="com.lagou.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean>
- 集合数据类型:list,set,map,properties
<bean id="user" class="com.lagou.domain.User"> <property name="username" value="jack"/> <property name="age" value="18"/> </bean> <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"> <property name="list"> <list> <value>aaa</value> <ref bean="user"></ref> </list> </property> </bean> <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"> <property name="set"> <list> <value>bbb</value> <ref bean="user"></ref> </list> </property> </bean> <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"> <property name="array"> <array> <value>ccc</value> <ref bean="user"></ref> </array> </property> </bean> <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"> <property name="map"> <map> <entry key="k1" value="ddd"/> <entry key="k2" value-ref="user"></entry> </map> </property> </bean> <bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"> <property name="properties"> <props> <prop key="k1">v1</prop> <prop key="k2">v2</prop> <prop key="k3">v3</prop> </props> </property> </bean>
- 普通数据类型
- <property>标签:属性注入 name属性:属性名称 value属性:注入的普通属性值 ref属性:注入的对象引用值 <list><set><array><map><props>
- import导入 <import resource= "application-xxx.xml"/>
- 同一个xml文件不能有同名bean,否则会报错
- 多个xml文件可以有同名bean,后加载的会覆盖前面加载的bean
7.基于spring.xml整合的DbUtils
- 准备数据库环境
CREATE DATABASE `spring_db`; USE `spring_db`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL, `money` double DEFAULT NULL, PRIMARY KEY (`id`) ) ; insert into `account`(`id`,`name`,`money`) values (1,'tom',1000), (2,'jerry',1000);
- 创建java项目,导入坐标
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
- 编写Account实体类
package com.domain; public class Account { private int id; private String name; private double money; @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } }
- 编写AccountDao接口和实现类
package com.dao.impl; import com.dao.AccountDao; import com.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.List; public class AccountDaoImp implements AccountDao { private QueryRunner qr; public QueryRunner getQr() { return qr; } public void setQr(QueryRunner qr) { this.qr = qr; } public List<Account> findAll() { List<Account> query=null; String sql="select * from account"; try { query= qr.query(sql, new BeanListHandler<Account>(Account.class)); } catch (SQLException e) { e.printStackTrace(); } return query; } public Account findById(Integer id) { Account account=null; try { String sql="select * from account where id=?"; account = qr.query(sql, new BeanHandler<Account>(Account.class),id); } catch (SQLException e) { e.printStackTrace(); } return account; } public void save(Account account) { try { String sql="insert into account values (null,?,?)"; qr.update(sql, account.getName(),account.getMoney()); } catch (SQLException e) { e.printStackTrace(); } } public void update(Account account) { try { String sql="update account set name=?, money = ? where id=?"; qr.update(sql, account.getName(),account.getMoney(),account.getId()); } catch (SQLException e) { e.printStackTrace(); } } public void delete(Integer id) { try { String sql="delete from account where id=?"; qr.update(sql, id); } catch (SQLException e) { e.printStackTrace(); } } }
- 编写AccountService接口和实现类
package com.service.impl; import com.dao.AccountDao; import com.domain.Account; import com.service.AccountService; import java.util.List; public class AccountServiceImp implements AccountService { private AccountDao accountDao; public AccountDao getAccountDao() { return accountDao; } public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public List<Account> findAll() { return accountDao.findAll(); } public Account findById(Integer id) { return accountDao.findById(id); } public void save(Account account) { accountDao.save(account); } public void update(Account account) { accountDao.update(account); } public void delete(Integer id) { accountDao.delete(id); } }
- 编写spring核心配置文件
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!-- datasource--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- queryrunner--> <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <!-- accountdao--> <bean id="accountDao" class="com.dao.impl.AccountDaoImp"> <property name="qr" ref="queryRunner"></property> </bean> <!-- acocuntservice--> <bean id="accountService" class="com.service.impl.AccountServiceImp"> <property name="accountDao" ref="accountDao"></property> </bean> </beans>
- 编写测试代码
package com.test; import com.domain.Account; import com.service.AccountService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class test { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = (AccountService) applicationContext.getBean("accountService"); @Test public void test01(){ List<Account> accountList = accountService.findAll(); for (Account account : accountList) { System.out.println(account); } } @Test public void test02(){ Account account = new Account(); account.setName("lucy"); account.setMoney(888d); accountService.save(account); } @Test public void test03(){ Account account = accountService.findById(3); System.out.println(account); } @Test public void test04(){ Account account = new Account(); account.setId(3); account.setName("jack"); account.setMoney(9999d); accountService.update(account); } @Test public void test05(){ accountService.delete(3); } }
8. spring注解
- Spring常用注解主要是替代 <bean> 的配置
JDK11以后完全移除了javax扩展导致不能使用@resource注解
<dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency>
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法
<!--注解的组件扫描--> <context:component-scan base-package="com.lagou"></context:component-scan>
- 新注解用于解决其他配置
非自定义的Bean的配置:<bean> 加载properties文件的配置:<context:property-placeholder> 组件扫描的配置:<context:component-scan> 引入其他文件:<import>
注解 | 说明 |
@Configuration | 用于指定当前类是一个Spring 配置类,当创建容器时会从该类上加载注解 |
@Bean | 使用在方法上,标注将该方法的返回值存储到 Spring 容器中 |
@PropertySource | 用于加载 properties 文件中的配置 |
@ComponentScan | 用于指定 Spring 在初始化容器时要扫描的包 |
@Import | 用于导入其他配置类 |
- 整合Junit:在普通的测试类中,需要开发者手动加载配置文件并创建Spring容器,然后通过Spring相关API获得Bean实例,可以让SpringJunit负责创建Spring容器来简化这个操作,开发者可以直接在测试类注入Bean实例;但是需要将配置文件的名称告诉它
- 导入spring集成Junit的坐标
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
- 使用@Runwith注解替换原来的运行器
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
9.完全注解进行DbUtils开发
- pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springdb</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--resource 注解不可用,因为JDK11以后完全移除了javax扩展--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> </dependency> </dependencies> </project>
- jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false jdbc.username=root jdbc.password=123456
- 核心配置类与数据配置
package com.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; @PropertySource("classpath:jdbc.properties") public class DataConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean("dataSource") public DataSource getDataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } } package com.config; import com.alibaba.druid.pool.DruidDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import javax.sql.DataSource; @Configuration @ComponentScan("com") @Import(DataConfig.class) public class SpringConfig { @Bean("queryRunner") public QueryRunner getQueryRunner(@Autowired DataSource dataSource){ QueryRunner queryRunner = new QueryRunner(dataSource); return queryRunner; } }
- 其他
package com.domain; public class Account { private int id; private String name; private double money; @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } } package com.dao.impl; import com.dao.AccountDao; import com.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.List; @Repository("accountDao") public class AccountDaoImp implements AccountDao { @Autowired private QueryRunner queryRunner; public List<Account> findAll() { List<Account> query=null; String sql="select * from account"; try { query= queryRunner.query(sql, new BeanListHandler<Account>(Account.class)); } catch (SQLException e) { e.printStackTrace(); } return query; } public Account findById(Integer id) { Account account=null; try { String sql="select * from account where id=?"; account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id); } catch (SQLException e) { e.printStackTrace(); } return account; } public void save(Account account) { try { String sql="insert into account values (null,?,?)"; queryRunner.update(sql, account.getName(),account.getMoney()); } catch (SQLException e) { e.printStackTrace(); } } public void update(Account account) { try { String sql="update account set name=?, money = ? where id=?"; queryRunner.update(sql, account.getName(),account.getMoney(),account.getId()); } catch (SQLException e) { e.printStackTrace(); } } public void delete(Integer id) { try { String sql="delete from account where id=?"; queryRunner.update(sql, id); } catch (SQLException e) { e.printStackTrace(); } } } package com.dao; import com.domain.Account; import java.util.List; public interface AccountDao { public List<Account> findAll(); public Account findById(Integer id); public void save(Account account); public void update(Account account); public void delete(Integer id); } package com.service.impl; import com.dao.AccountDao; import com.domain.Account; import com.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service("accountService") public class AccountServiceImp implements AccountService { @Autowired // @Qualifier("accountDao") // @Resource(name = "accountDao") private AccountDao accountDao; public List<Account> findAll() { return accountDao.findAll(); } public Account findById(Integer id) { return accountDao.findById(id); } public void save(Account account) { accountDao.save(account); } public void update(Account account) { accountDao.update(account); } public void delete(Integer id) { accountDao.delete(id); } } package com.service; import com.domain.Account; import java.util.List; public interface AccountService { public List<Account> findAll(); public Account findById(Integer id); public void save(Account account); public void update(Account account); public void delete(Integer id); }
- 测试
package com.test; import com.config.SpringConfig; import com.domain.Account; import com.service.AccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringConfig.class}) public class test { //使用注解方式 //ApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class); // AccountService accountService = (AccountService) applicationContext.getBean("accountService"); @Autowired private AccountService accountService; @Test public void test01(){ List<Account> accountList = accountService.findAll(); for (Account account : accountList) { System.out.println(account); } } @Test public void test02(){ Account account = new Account(); account.setName("lucy"); account.setMoney(888d); accountService.save(account); } @Test public void test03(){ Account account = accountService.findById(3); System.out.println(account); } @Test public void test04(){ Account account = new Account(); account.setId(3); account.setName("jack"); account.setMoney(9999d); accountService.update(account); } @Test public void test05(){ accountService.delete(3); } }
标签:account,SpringIOC,Account,id,import,com,public 来源: https://www.cnblogs.com/forever-fate/p/15016561.html