spring的注解配置,没有xml

通常,我们使用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
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值