调用xml文件的bean
AcTest.class
package com.zyz.db; import com.zyz.dao.PersonDao; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * Created by zyz on 2016-8-5. */ public class AcTest { public static void main(String[] args){ // 方法1:使用FileSystemXmlApplicationContext ApplicationContext ac1=new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext-jdbc.xml"); DriverManagerDataSource dataSource=(DriverManagerDataSource) ac1.getBean("dataSource"); System.out.println(dataSource.getUsername()); // 方法2:使用ClassPathXmlApplicationContext ApplicationContext ac2=new ClassPathXmlApplicationContext("beans.xml"); PersonDao personDao=(PersonDao)ac2.getBean("personDao");
System.out.println(personDao.getVersion());
System.out.println(personDao.getPersons().get(0).getName()); } }
方法1:只要指定xml文件的在项目中的相对位置
方法2:从classpath位置读xml文件,即编译后class文件存放的位置.
可以先将xml文件放入resources文件夹,然后将resources文件夹加入到classpath,在idea中:
"File"->"Project Structure",出现对话框,添加resources文件夹,编译运行后,系统会将xml文件复制到classes文件夹中
applicationContext-jdbc.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:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd "> <!--配置mysql数据库--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <!--jdbcTemplate和数据库关联--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name = "dataSource" ref="dataSource"/> </bean> </beans>
beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="personDao" class="com.zyz.dao.PersonDao"> <property name="version"> <value>3.85</value> </property> </bean> </beans>