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:component-scan base-package="com.itheima"></context:component-scan>
<!--创建queryRunner对象, 需要数据源对象,创建数据源对象,通过构造方法注入-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<!--通过构造方法参数类型注入 dataSource-->
<constructor-arg type="javax.sql.DataSource" ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--通过set方法注入-->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--引入外部属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
</beans>
dao包的accountDao 。 @Autowired的自动注入queryRunner是用的set方法注入,需要添加set方法,这里用的xml配置,不添加也可以。
xml配置和注解的区别就是注解配有配置类
@Service("accountService")
public class AccountServiceImpl implements AccountService {
/* AccountDao accountDao = new AccountDaoImpl();*/
//引入accountDao的注入
@Autowired
AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public Account findIdAccount(Integer id) {
return accountDao.findIdAccount(id);
}
}
纯注解模式:
class SpringConfiguration配置
@Configuration
@ComponentScan("com.itheima")
@Import(JDBCConfiguration.class)
public class SpringConfiguration {
}
class JDBCConfiguration配置。注意里面@Bean的使用
public class JDBCConfiguration {
@Bean(" queryRunner")
public QueryRunner createQueryRunner(DataSource dataSource){
QueryRunner queryRunner = new QueryRunner(dataSource);
return queryRunner;
}
/*@Bean 具有以下四个属性:
name – 指定一个或者多个 Bean 的名字。这等价于 XML 配置中 的 name 属性。
initMethod – 容器在初始化完 Bean 之后,会调用该属性指定的方法。这等价于 XML 配置中 的 init-method 属性。 */
@Bean("dataSource")
public DataSource createDaDataSources(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf8");
dataSource.setUser("root");
dataSource.setPassword("root");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}