Spring总结一、IOC1、spring基本坐标<properties>
<spring.version>5.0.5.RELEASE</spring.version>
</properties>
<!--导入spring的context坐标,context依赖core、beans、expression-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies> 2、核心配置文件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">
<!-- 将userDao注入到spring容器内,由spring容器管理-->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
</beans>3、使用Spring的API获得Bean实例
@Test
public void test1(){
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("applicationContext.xml");
//UserDao userDao = (UserDao) applicationContext.getBean("userDao");
UserDao userDao = (UserDao) applicationContext.getBean(UserDao.class);
userDao.save();
}4、Bean实例化三种方式1)使用无参构造方法实例化(掌握)
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>2)工厂静态方法实例化(了解)
public class StaticFactoryBean {
public static UserDao createUserDao(){
return new UserDaoImpl();
}
}
<bean id="userDao" class="com.itheima.factory.StaticFactoryBean"
factory-method="createUserDao" />3)工厂实例方法实例化(了解)
public class DynamicFactoryBean {
public UserDao createUserDao(){
return new UserDaoImpl();
}
}
<bean id="factoryBean" class="com.itheima.factory.DynamicFactoryBean"/>
<bean id="userDao" factory-bean="factoryBean" factory-method="createUserDao"/>5、Bean的依赖注入(set方法)1)在UserServiceImpl中添加setUserDao方法
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
} 2)配置Spring容器调用set方法进行注入
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>二、Spring配置数据源1、开发步骤①导入数据源的坐标和数据库驱动坐标 ②创建数据源对象 ③设置数据源的基本连接数据 ④使用数据源获取连接资源和归还连接资源
①导入c3p0或druid和Mysql驱动的坐标
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
|