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

 

說明能夠從資源文件中拿到指定的數據。

 

 

未完待續......

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM