spring 依赖注入案例(bean.xml以及注解两种配置方式)
准备工作:
Account实体类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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接口及其实现类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 { }