Spring概述
- spring 是一个开源框架
- spring为简化企业级开发而生,使用Spring,JavaBean就可以实现很多以前要靠EJB(Enterprise JavaBean)才能实现的功能。
- Spring是一个IOC(控制反转)(DI)和AOP(面向切面编程)容器框架。
- Spring的优良特性
1 非侵入式:基于Spring开发的应用中的对象可以不依赖于Spring的API(实现接口或继承类,又叫做轻量级的)
2 依赖注入:DI——Dependency Injection,反转控制(IOC)最经典的实现。
3 面向切面编程:Aspect Oriented Programming——AOP
4 容器:Spring是一个容器,因为它包含并且管理应用对象的生命周期
5 组件化:Spring实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用XML和Java注解组合这些对象。 - 一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring 自身也提供了表述层的SpringMVC和持久层的Spring JDBC)。
搭建Spring运行时环境
-
加入JAR包
1 Spring自身JAR包:spring-framework-4.0.0.RELEASE\libs目录下
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
2 commons-logging-1.1.1.jar -
创建Spring配置文件
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialPoolSize" value="10"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.waiwai.mapper" />
</bean>
- 创建实体类
package com.waiwai.pojo;
import org.springframework.stereotype.Component;
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 接口 与xml文件
package com.waiwai.mapper;
import com.waiwai.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> listUsers();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.waiwai.mapper.UserMapper">
<select id="listUsers" resultType="user">
select id,
username,
password
from
empuser
</select>
</mapper>
- 创建service层
public interface UserService {
public List<User> findUsers();
}
在测试类中测试连接
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext1.xml");
UserServiceImpl userServiceImpl =(UserServiceImpl) context.getBean("userServiceImpl");
List<User> userByAll = userServiceImpl.findUsers();
System.out.println(userByAll.size());
测试结果