一、配置非自定义的Bean(数据源DataSource模型)
DBCP数据源:
导入dbcp的jar包:dbcp+pool+connector
代码实现:
public class CommonsTest {
//测试手动创建dbcp的数据源对象
@Test
public void getDBCPConnection() throws SQLException {
//创建数据源对象
BasicDataSource basicDataSource = new BasicDataSource();
//设置数据库的基本参数
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql:///test");
basicDataSource.setUsername("root");
basicDataSource.setPassword("root");
//从数据源中获得连接资源
Connection connection = basicDataSource.getConnection();
//jdbc操作
System.out.println(connection);
}
}
C3P0数据源:
导入c3p0的jar包:c3p0+connector
代码实现:
public class CommonsTest {
//测试手动创建c3p0的数据源对象
@Test
public void getC3P0Connection() throws SQLException, PropertyVetoException {
//创建数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//设置数据库的基本参数
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql:///test");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("root");
//从数据源中获得连接资源
Connection connection = comboPooledDataSource.getConnection();
//jdbc操作
System.out.println(connection);
}
//测试手动创建c3p0的数据源对象,配置信息读取jdbc.properties
@Test
public void getPropertiesConnection() throws SQLException, PropertyVetoException {
//读取jdbc.properties配置文件
ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
//创建数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//设置数据库的基本参数
comboPooledDataSource.setDriverClass(resourceBundle.getString("jdbc.driver"));
comboPooledDataSource.setJdbcUrl(resourceBundle.getString("jdbc.url"));
comboPooledDataSource.setUser(resourceBundle.getString("jdbc.username"));
comboPooledDataSource.setPassword(resourceBundle.getString("jdbc.password"));
//从数据源中获得连接资源
Connection connection = comboPooledDataSource.getConnection();
//jdbc操作
System.out.println(connection);
}
}
在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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置dbcp数据源 -->
<bean id="dataSourceDBCP" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置C3P0数据源 -->
<bean id="dataSourceC3P0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 将jdbc.properties文件加载到spring的容器中 需要用到context命名空间
classpath:类加载路径 开发环境下就是src
-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置C3P0数据源 -->
<bean id="dataSourceC3P0Properties" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
测试
public class CommonsTest {
//测试从spring中获得C3P0实例对象,通过加载配置文件jdbc.properties获得参数
@Test
public void test4() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) applicationContext.getBean("dataSourceC3P0Properties");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
//测试从spring中获得C3P0实例对象
@Test
public void test3() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) applicationContext.getBean("dataSourceC3P0");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
//测试从spring中获得DBCP实例对象
@Test
public void test2() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) applicationContext.getBean("dataSourceDBCP");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}
二、Spring的注解开发(基于注解的IOC配置)
Spring原始注解(重点)
出现的目的主要是对自定义的Bean的xml配置的替代。
开发步骤:
1、导入额外jar包:spring-aop.jar
2、在xml中开启组件扫描
<!-- 组件扫描:告知spring容器哪些包下的bean需要被扫描 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
3、在实体Bean上使用注解进行开发
@Component("customer")
public class Customer {
@Value("阿狸")
private String name;
@Value("20")
private int age;
@Override
public String toString() {return "Customer{" +"name='" + name + '\'' +", age=" + age +'}';}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
}
//@Component("customerDao")
@Service("customerDao") // service层
//@Controller("customerDao") // web层
//@Repository("customerDao")// dao层
//@Scope("prototype")
@Scope("singleton")
public class CustomerDaoImpl implements CustomerDao {
@Autowired//按照类型进行匹配
//@Qualifier("customer") //此处@Qualifier是按照名称匹配 但是在此处@Qualifier结合@Autowired一起使用
//@Resource(name="customer") //@Resource=@Autowired+@Qualifier
private Customer customer;
@Override
public void save() {System.out.println("添加客户信息...");}
@Override
public void delete() {System.out.println("删除客户信息...");}
@Override
public void update() {System.out.println("修改客户信息...");}
@Override
public void find() {System.out.println("查找客户信息...");}
@Override
public void show() {System.out.println(customer);}
@PostConstruct//在构造之后执行
public void init(){System.out.println("init...");}
@PreDestroy//在销毁之前执行
public void destroy(){System.out.println("destroy...");}
}
4、测试
public class CommonsTest {
//测试从spring中获得Dao实例对象
@Test
public void test5(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerDaoImpl customerDao = (CustomerDaoImpl) applicationContext.getBean("customerDao");
customerDao.save();
customerDao.delete();
customerDao.update();
customerDao.find();
customerDao.show();
applicationContext.close();
}
}
注解的详解:
IoC:创建对象
@Component(该Bean对象的标识/id):在需要被spring进行实例化Bean上,参数字符串可以不写,默认是当前类名的首字母小写
@Controller:控制器 使用web层的Bean上 例如Action
@Service:服务 使用service层的Bean 例如CustomerServiceImpl
@Repository: 仓库 使用dao层的Bean上 例如CustomerDaoImpl
DI:依赖注入,注解的注入可以省略set方法对象属性注入:
@Autowired:自动按照实体的类型进行注入
@Qualifier("customerDao") //此处@Qualifier是按照名称匹配 但是在此处@Qualifier结合@Autowired一起使用
@Resource(name="customerDao") //@Resource=@Autowired+@Qualifier普通属性注入:
@Value(值)
其他:
@Scope:配置bean的作用范围,取值singleton(默认)和prototype
@PostConstruct:指定初始化方法 //在构造之后执行
@PreDestroy:指定销毁方法 //在销毁之前执行
【注意】重点注解:@Controller、@Service、@Repository、@Autowired、@Scope
【注意】开发准则:Bean是自定义那么使用注解配置、Bean是非自定义的那么使用xml配置
Spring新注解(次重点)
Spring的新注解出现的目的完全替代xml配置文件
使用配置类 替代 xml文件
使用注解 替代 标签
//连接池参数配置
@PropertySource({"classpath:jdbc.properties"})//加载jdbc.properties文件
public class DataSourceConfiguration {
@Value("${jdbc.driver}")//匹配spring容器中的key
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name="dataSource") //将该方法的返回值以指定的名称存储到spring容器中
public DataSource getDataSource() throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置数据库的基本参数
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
//连接池配置类
@Configuration //标注该类是一个spring的配置类
@ComponentScan("com.itheima")//组件扫描
@Import({DataSourceConfiguration.class})//引入其他的配置类
public class SpringConfiguration {}
测试
public class CommonsTest {
@Test
//测试加载spring的配置类 获得实体Bean
public void test2() throws Exception{
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService customerService = (CustomerService) app.getBean("customerService");//测试@ComponentScan("com.itheima")
customerService.save();
DataSource dataSource = (DataSource) app.getBean("dataSource");//测试@Bean(name="dataSource")
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}
注解的详解:
@Configuration //标注该类是一个spring的配置类
@ComponentScan("com.itheima") //组件扫描
@Import({DataSourceConfiguration.class}) //引入其他的配置类
@PropertySource({"classpath:jdbc.properties"}) //加载jdbc.properties文件
@Value("${jdbc.driver}") //匹配spring容器中的key
@Bean(name="dataSource") //将该方法的返回值以指定的名称存储到spring容器中
三、Spring集成Junit(大篇幅测试建议使用)
开发步骤:
1、导入额外的jar
2、通过注解的形式指定测试类 和 配置文件
执行测试类:@RunWith(SpringJUnit4ClassRunner.class)
指定配置文件(类):@ContextConfiguration("classpath:applicationContext.xml")
3、测试spring容器中的哪个对象就通过注解注入哪个对象
4、编写测试方法
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml") //加载配置文件
@ContextConfiguration(classes={SpringConfiguration.class}) //加载配置类
public class SpringJunitTest {
@Autowired
private CustomerDao customerDao;
@Autowired
private CustomerService customerService;
@Test
public void test1(){
customerDao.save();
}
@Test
public void test2(){
customerService.save();
}
}