准備工作:
Account實體類

package com.itheima.domain; /** * 賬戶的實體類 * */ public class Account { private Integer id; private String name; private Float money; public Integer getId() { return id; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } }
IAccountDao接口及其實現類:使用QueryRunner操作mysql

package com.itheima.dao.impl; import com.itheima.dao.IAccountDao; import com.itheima.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.util.List; public class AccountDaoImpl implements IAccountDao { private QueryRunner runner; public void setRunner(QueryRunner runner) { this.runner = runner; } public List<Account> findAllAccount() { try { return runner.query("select * from account", new BeanListHandler<Account>(Account.class)); }catch (Exception e){ throw new RuntimeException(e); } } public Account findAccountById(Integer integer) { try { return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),integer); }catch (Exception e){ throw new RuntimeException(e); } } public void saveAccount(Account account) { try { runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney()); }catch (Exception e){ throw new RuntimeException(e); } } public void updateAccount(Account account) { try { runner.update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId()); }catch (Exception e){ throw new RuntimeException(e); } } public void deleteAccount(Integer accountId) { try { runner.update("delete from account where id=?",accountId); }catch (Exception e){ throw new RuntimeException(e); } } }
IAccountService接口及其實現類

package com.itheima.service.impl; /* * 賬戶的業務層實現類 * */ import com.itheima.dao.IAccountDao; import com.itheima.domain.Account; import com.itheima.service.IAccountService; import java.util.List; public class AccountServiceImpl implements IAccountService { private IAccountDao accountDao; public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; } public List<Account> findAllAccount() { return accountDao.findAllAccount(); } public Account findAccountById(Integer integer) { return accountDao.findAccountById(integer); } public void saveAccount(Account account) { accountDao.saveAccount(account); } public void updateAccount(Account account) { accountDao.updateAccount(account); } public void deleteAccount(Integer accountId) { accountDao.deleteAccount(accountId); } }
使用bean.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"> <!--配置service對象--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <!--用set方式注入dao--> <property name="accountDao" ref="accountDao"></property> </bean> <!--配置dao對象--> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"> <!--用set方式注入QueryRunner--> <property name="runner" ref="runner"></property> </bean> <!--配置QueryRunner,采用多例模式--> <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!--用構造函數注入數據源--> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <!--配置數據源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--鏈接數據庫的必備信息--> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/eesy?useSSL=false&serverTimezone=GMT%2B8"></property> <property name="user" value="root"></property> <property name="password" value="nimahaoma49"></property> </bean> </beans>
修改為使用注解進行配置
修改IAccountDao接口及其實現類,刪掉setrunner方法
@Repository("accountDao") //加在類處 @Autowired//加在runnner聲明處
修改IAccountService接口及其實現類
@Service("accountService") //加在類處 @Autowired private IAccountDao accountDao;//自動注入dao /*public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; } 注釋掉set方法 */
修改bean.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"> <!--告知spring在創建容器時要掃描的包--> <context:component-scan base-package="com.itheima"> </context:component-scan> <!--配置QueryRunner,采用多例模式--> <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!--用構造函數注入數據源--> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> <!--配置數據源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--鏈接數據庫的必備信息--> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/eesy?useSSL=false&serverTimezone=GMT%2B8"></property> <property name="user" value="root"></property> <property name="password" value="nimahaoma49"></property> </bean> </beans>
嘗試完全使用注解代替bean.xml進行配置
新建一個配置類 SpringConfiguration
package config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import javax.sql.DataSource; /** * 該類是一個配置類,它的作用和bean.xml是一樣的 * spring中的新注解 * @Configuration: * 作用:指定當前類是一個配置類 * @ComponentScan * 作用:用於通過注解指定spring在創建容器時要掃描的包 * 屬性: * value:它和basePackages的作用一樣,用於指定創建容器時要掃描的包 * 我們使用此注解就等同於在xml中配置了 * <context:component-scan base-package="com.itheima"></context:component-scan> * @Bean * 作用:用於把當前方法的返回值作為bean對象存入spring的ioc容器中 * 屬性: * name:用於指定bean的id,默認值(當不寫時)是當前方法的名稱 * 細節: * 當我們使用注解配置方法時,如果方法有參數,spring框架回去容器中查找有沒有可用的bean對象 * 查找的方式和Autowired注解的作用是一樣的 */ @Configurable @ComponentScan(basePackages = "com.itheima") public class SpringConfiguration { /** * 用於創建一個QueryRunner對象 * @param dataSource * @return */ @Bean(name="runner") public QueryRunner createQueryRunner(DataSource dataSource){ return new QueryRunner(dataSource); } /** * 創建數據源對象 * @return */ @Bean(name="dataSource") public DataSource createDataSource(){ try{ ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/eesy?useSSL=false&serverTimezone=GMT%2B8"); ds.setUser("root"); ds.setPassword("nimahaoma49"); return ds; }catch (Exception e){ e.printStackTrace(); } return null; } }
同時獲取核心容器時改變方法
//1.獲取容器 //ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
這樣就可以把bean.xml完全刪掉了
一些新配置注解
@Import(JdbcConfig.class)
可以用在父配置類下指定很多子配置類
@Import * 作用:用於導入其他配置類,有該注解的是父配置類,導入的是子配置類 * 屬性: * value:用於指定其他配置類的字節碼
/** @Import * 作用:用於導入其他配置類,有該注解的是父配置類,導入的是子配置類 * 屬性: * value:用於指定其他配置類的字節碼 * @PropertySource * 作用:用於指定properties文件的位置 * 屬性: * value:指定文件的名稱和路徑 * 關鍵字classpath:表示類路徑下 */
比如將jdbc的配置移動到子配置類JdbcConfig中

package config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import javax.sql.DataSource; /** * 和數據庫相關的配置類 * */ @Configuration //此處Configurable不可省略 public class JdbcConfig { /** * 用於創建一個QueryRunner對象 * @param dataSource * @return */ @Bean(name="runner") @Scope("singleton") public QueryRunner createQueryRunner(DataSource dataSource){ return new QueryRunner(dataSource); } /** * 創建數據源對象 * @return */ @Bean(name="dataSource") public DataSource createDataSource(){ try{ ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/eesy?useSSL=false&serverTimezone=GMT%2B8"); ds.setUser("root"); ds.setPassword("nimahaoma49"); return ds; }catch (Exception e){ e.printStackTrace(); } return null; } }
此時父配置類SpringConfiguration 只要如下即可
@Configuration @ComponentScan(basePackages = "com.itheima") @Import(JdbcConfig.class) public class SpringConfiguration { }