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

 

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

 

 

未完待续......

 

posted @ 2018-11-07 17:45  轻抚丶两袖风尘  阅读(1310)  评论(0编辑  收藏  举报