spring学习第二天
使用 spring 的 IoC 的实现用户的crud(基于xml)
注意这个案例中使用三个技术
:1、c3p0
2、dbassit
3、spring实现ioc管理
环境搭建
<?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>springTest2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
这里有可能出现mysql的版本和c3p0数据池技术向冲突的情况,适当调低mysql的版本
创建数据库和编写实体类
package doMain;
import java.util.Date;
public class User {
int id;
String username;
Date birthday;
String sex;
String address;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
编写持久层代码
package dao;
import doMain.User;
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 UserDaoImpl implements IUserDao{
QueryRunner queryRunner;
public QueryRunner getQueryRunner() {
return queryRunner;
}
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
public List<User> findAll() throws SQLException {
String sql="select * from user";
List<User> users= queryRunner.query(sql,new BeanListHandler<User>(User.class));
return users;
}
public User findById(int i) {
String sql="select * from user where id=?";
User user = null;
try {
user = queryRunner.query(sql, new BeanHandler<User>(User.class), i);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return user;
}
public boolean saveUser(User user) {
String sql="insert into user (username,birthday,sex,address) values (?,?,?,?)";
try {
queryRunner.update(sql,user.getUsername(),user.getBirthday(),user.getSex(),user.getAddress());
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
return false;
}
}
public boolean deleteUser(int i) {
String sql="delete from user where id=?";
try {
queryRunner.update(sql,i);
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
return false;
}
}
}
package service;
import dao.IUserDao;
import doMain.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
import java.util.List;
public class UserServiceImpl implements IUserService {
IUserDao dao;
public IUserDao getDao() {
return dao;
}
public void setDao(IUserDao dao) {
this.dao = dao;
}
public List<User> findAll() throws SQLException {
List<User> all = dao.findAll();
return all;
}
public User findById(int i) {
return dao.findById(i);
}
public boolean saveUser(User user) {
return dao.saveUser(user);
}
public boolean deleteUser(int i) {
return dao.deleteUser(i);
}
}
创建并编写配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="dao.UserDaoImpl">
<property name="queryRunner" ref="queryRunner"></property>
</bean>
<bean id="userService" class="service.UserServiceImpl">
<property name="dao" ref="userDao"></property>
</bean>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
测试类代码
import com.sun.xml.internal.txw2.output.DumpSerializer;
import doMain.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IUserService;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class test {
private ApplicationContext context;
private IUserService service;
@Before
public void init(){
context = new ClassPathXmlApplicationContext("bean.xml");
service = (IUserService) context.getBean("userService");
}
@Test
public void findAll() throws SQLException {
List<User> all = service.findAll();
for (User u :
all) {
System.out.println(u);
}
}
@Test
public void findById() throws SQLException {
User user = service.findById(53);
System.out.println(user);
}
@Test
public void saveUser() throws SQLException {
User user=new User();
user.setUsername("spring");
user.setAddress("jinhua");
user.setBirthday(new Date());
user.setSex("男");
boolean b = service.saveUser(user);
System.out.println(b);
}
@Test
public void deleteUser() throws SQLException {
boolean b = service.deleteUser(55);
System.out.println(b);
}
}
使用 spring 的 IoC 的实现用户的crud(基于注解)
添加依赖
<?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>springTest3</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
如果报这个错就说明依赖版本不兼容,适当降低版本
java.lang.NoClassDefFoundError: org/springframework/core/metrics/ApplicationStartup
Dao
package dao;
import doMain.User;
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.Component;
import java.sql.SQLException;
import java.util.List;
@Component("userDao")
public class UserDaoImpl implements IUserDao{
@Autowired
QueryRunner queryRunner;
public List<User> findAll() throws SQLException {
String sql="select * from user";
List<User> users= queryRunner.query(sql,new BeanListHandler<User>(User.class));
return users;
}
public User findById(int i) {
String sql="select * from user where id=?";
User user = null;
try {
user = queryRunner.query(sql, new BeanHandler<User>(User.class), i);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return user;
}
public boolean saveUser(User user) {
String sql="insert into user (username,birthday,sex,address) values (?,?,?,?)";
try {
queryRunner.update(sql,user.getUsername(),user.getBirthday(),user.getSex(),user.getAddress());
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
return false;
}
}
public boolean deleteUser(int i) {
String sql="delete from user where id=?";
try {
queryRunner.update(sql,i);
return true;
} catch (SQLException throwables) {
throwables.printStackTrace();
return false;
}
}
}
这里使用注解@Component
service
package service;
import dao.IUserDao;
import doMain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.List;
@Component("userService")
public class UserServiceImpl implements IUserService {
@Autowired
IUserDao dao;
public List<User> findAll() throws SQLException {
List<User> all = dao.findAll();
return all;
}
public User findById(int i) {
return dao.findById(i);
}
public boolean saveUser(User user) {
return dao.saveUser(user);
}
public boolean deleteUser(int i) {
return dao.deleteUser(i);
}
}
这里使用@AutoWired
意思就是从容器中寻找,找到了就赋值上,有多个相同类型就按照名称进行寻找,再找不到就报错。
常用的还有@Qualifier
@resource
@Value
@Scope
@PostConstruct
@PreDestroy
配置文件
注意此时queryRunner还是需要在xml文件中配置,另外注意,利用context:component去设置扫描的包时,如果目录是直接放在java目录下,然后配置上java,是行不通的,最好把代码放在一个统一的包路径下,或者分开配置扫描路径
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="service"></context:component-scan>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
测试代码
注意,第一个service对象还是需要从配置文件中获取,因为这时候使用的junit并没有与spring想结合,junit并不清楚你有没有使用spring,因此就没法自动获取容器,需要手动获取容器,然后从容器中获取service对象,如果想彻底去掉xml配置就需要使用后面讲到的@ContextConfiguration和@RunWith注解。
import com.sun.xml.internal.txw2.output.DumpSerializer;
import doMain.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IUserService;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class test {
private ApplicationContext context;
private IUserService service;
@Before
public void init(){
context = new ClassPathXmlApplicationContext("bean.xml");
service = context.getBean("userService",IUserService.class);
}
@Test
public void findAll() throws SQLException {
List<User> all = service.findAll();
for (User u :
all) {
System.out.println(u);
}
}
@Test
public void findById() throws SQLException {
User user = service.findById(53);
System.out.println(user);
}
@Test
public void saveUser() throws SQLException {
User user=new User();
user.setUsername("spring");
user.setAddress("jinhua");
user.setBirthday(new Date());
user.setSex("男");
boolean b = service.saveUser(user);
System.out.println(b);
}
@Test
public void deleteUser() throws SQLException {
boolean b = service.deleteUser(55);
System.out.println(b);
}
}
spring的纯注解配置
使用到的新注解
@Configuration
获取容器使用方式:
这里就是用配置类取代了xml配置
示例代码:
可以看到这里给一个类加上该注解之后表明该类为配置类,在后面就可以使用AnnotationConfigApplicationContext()方法去加载获取容器,但是这里其实可以不写上该配置类的名称,因为它已经注上了@Configuration注解,但是如果不写这个注解就必须在AnnotationConfigApplicationContext()中传入配置类的class文件。
@ComponentScan
在配置类上写上该注解以用于指定初始化时扫描的包,也可以使用ComponentScans来添加多个Componentscan注解如下:
@Bean
示例注解:
@PropertySource
示例代码:
@Configuration
@ComponentScans( {@ComponentScan("dao"),@ComponentScan("service")})
@PropertySource("jdbc.properties")
public class Config {
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Bean("queryRunner")
@Scope("prototype")
public QueryRunner getQueryRunner(javax.sql.DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean("dataSource")
public DataSource getDataSource(){
ComboPooledDataSource dataSource=new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setPassword(user);
dataSource.setUser(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}
我这里是写在resource目录下,所以直接写文件名即可。导入之后,在变量传值时,就可以使用spring的er表达式了,用${}去引用资源,传入key值去拿到我们想要的values值,
@Import
如果我们有多个配置类但是不想分开读取,而是一次性读取,就使用import注解,这样在读取主配置文件的时候就会把import中写入的从配置文件也配置进来。
spring整合junit
因为junit并不知道你有没有使用spring,因此无法自动获取容器,因此我们应该使用spring集成的junit,替换junit的运行器,让其在运行时,自动帮我们创建容器。
第一步:导入依赖jar包
这里有一点细节需要知道:
当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
第二步:使用@RunWith 注解替换原有运行器
这里替换的是springjunit4ClassRunner.class
第三步:使用@ContextConfiguration 指定 spring 配置文件的位置
改变了运行器之后还要告知从哪里获取容器这里可以获取xml配置,也可使用注解类
读取xml就是在前面加上locations
使用注解类就是在前面加上classes
第四步:使用@Autowired 给测试类中的变量注入数据
这时候我们测试类中的变量就可以从容器中获取值了