Spring 四:配置JDBC的注解使用方式。

建立jdbc-config.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url:jdbc=mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

配置jdbcDriver-config.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" xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:/jdbc-config.properties" />

</beans>

 

import java.sql.DriverManager;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;


@Configuration
@ImportResource("classpath:/jdbcDriver-config.xml")
public class JdbcConfig {
    
    @Value("${jdbc.url}")
    private String url;
    
    @Value("${jdbc.username}")
    private String username; 
    
    @Value("${jdbc.password}")
    private String password;
    
    

    
    @Bean
    public MyDriverManager myDriverManager() {
        return new MyDriverManager(url,username,password);
    }
     
    
    
}


package Annotation.Beans;

public class MyDriverManager {



    public MyDriverManager(String url, String username, String password) {
        System.out.println("url:"+url);
        System.out.println("username:"+username);
        System.out.println("password:"+password);
    }
}



public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("spring_annotation-config.xml");
        //用过ClassPathXmlApplicationContext获得配置文件的内容

        MyDriverManager manager=(MyDriverManager)classPathXmlApplicationContext.getBean("myDriverManager");
        System.out.println(manager.getClass().getName());
    }


 

 

在Main中调用输出一下,看能不能得到properties的值,如下是输出结果。

url:jdbc:mysql://localhost:3306/test
username:root
password:root

 

说明能够从资源文件中拿到指定的数据。

 

 

未完待续......

 

转载于:https://www.cnblogs.com/yangdagaoge/articles/9924044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值