使用xml和注解配置Spring ioc
xml配置使用步骤
1.创建maven工厂,导入相关jar包。
spring-context
mysql-connector-java
spring-test
commons-beanutils
c3p0
junit
commons-dbutils
2.创建实体类、持久层和业务层代码。(业务层中调用持久层的接口,不需申请对象,只声明和创建set方法即可(用于set注入)。持久层调用QueryRuner同理)
3.创建xml配置文件bean.xml。
1.引入xml的依赖。(在spring core中搜索“xmlns:”,第一个即可)
2.注入Service,其中使用set方法注入dao.
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
3.注入dao,其中用set方法注入QueryRunner.
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"></property>
</bean>
4.注入QueryRunner,利用构造函数方法注入dataSource.(注:QueryRunner为多例)
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
5.注入dataSource,并利用构造函数注入数据库连接参数。
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
4.创建测试类,测试方法。(注:利用spring整合junit)
1.使用junit提供的注解把main方法替换掉。
@RunWith(SpringJUnit4ClassRunner.class)
2.告知spring运行器,spring ioc是基于xml还是注解,并说明位置。
@ContextConfiguration(locations = "classpath:bean.xml")
3.自动注入接口类,利用接口类测试方法。
注解配置使用步骤
1.创建maven工厂,导入相关jar包。
spring-context
mysql-connector-java
spring-test
commons-beanutils
c3p0
junit
commons-dbutils
2.创建实体类、持久层和业务层代码。(业务层中调用持久层的接口,利用@Autowired注解自动注入持久层。持久层调用QueryRuner同理)
3.创建xml配置文件bean.xml。
1.引入xml的依赖。(在spring core中搜索“xmlns:context”,第一个即可)
2.注入QueryRunner,利用构造函数方法注入dataSource.(注:QueryRunner为多例)
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
3.注入dataSource,并利用构造函数注入数据库连接参数。
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
4.创建测试类,测试方法。(注:利用spring整合junit)
1.使用junit提供的注解把main方法替换掉。
@RunWith(SpringJUnit4ClassRunner.class)
2.告知spring运行器,spring ioc是基于xml还是注解,并说明位置。
@ContextConfiguration(locations = "classpath:bean.xml")
3.自动注入接口类,利用接口类测试方法。
基于注解和基于xml都可以将连接数据库的信息写入properties文件中,在配置文件中利用<context:property-placeholder location=“classpath:jdbc.properties”/>进行配置