通常,我们使用spring都是使用spring的xml配置文件配置,但是,spring也提供了注解配置的方式,具体配置方式如下:
创建一个属性文件,用来存放数据库连接信息:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
password=root
由于要使用注解配置,因此需要一个Java类作为IOC容器,我们将类名命名为SpringConfiguration,内容与xml配置方式相似,数据库操作我们仍然使用commons-dbutils包中的QueryRunner类,如下:
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/*
* 这个配置类,与spring配置文件一样
*
* */
@Configuration
@ComponentScan(basePackages = "cn.com.gjw")
@PropertySource("classpath:dataSource.properties")
public class SpringConfigruation {
//从属性文件中读取对应值
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
/**
* 用于创建一个QueryRunner对象,并且将对象存入ioc容器中。
* 相当于xml中的如下配置:
* <!--配置操作数据库的对象,必须依赖数据源-->
* <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
* <!--注入数据源-->
* <constructor-arg ref="c3p0"/>
* </bean>
* */
@Bean(value="runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 用于创建c3p0数据源,并将对象存入ioc容器。
* 相当于xml配置中的如下配置:
* <!--配置数据源-->
* <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
* <property name="driverClass" value="com.mysql.jdbc.Driver"/>
* <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
* <property name="use