基于 xml 的 IOC 案例
创建数据库
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
创建接口
IAccountDao
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
IAccountService
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param accountId
*/
void deleteAccount(Integer accountId);
}
创建实现类
AccountDaoImpl
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 accountId) {
try{
return runner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class),accountId);
} 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);
}
AccountServiceImpl
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 accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
}
创建账户实体类
Account
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setMoney(Float money) {
this.money = money;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Float getMoney() {
return money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
创建测试类
AccountServiceTest
public class AccountServiceTest {
@Test
public void testFindAll() {
// 1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到业务层对象
IAccountService iAccountService = applicationContext.getBean("accountService",IAccountService.class);
// 3.执行方法
List<Account> accounts = iAccountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
// 1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到业务层对象
IAccountService iAccountService = applicationContext.getBean("accountService",IAccountService.class);
// 3.执行方法
Account account = iAccountService.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("test");
account.setMoney(12345f);
// 1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到业务层对象
IAccountService iAccountService = applicationContext.getBean("accountService",IAccountService.class);
// 3.执行方法
iAccountService.saveAccount(account);
}
@Test
public void testUpdate() {
// 1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到业务层对象
IAccountService iAccountService = applicationContext.getBean("accountService",IAccountService.class);
// 3.执行方法
Account account = iAccountService.findAccountById(4);
account.setMoney(23456f);
iAccountService.updateAccount(account);
}
@Test
public void testDelete() {
// 1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到业务层对象
IAccountService iAccountService = applicationContext.getBean("accountService",IAccountService.class);
// 3.执行方法
iAccountService.deleteAccount(4);
}
}
配置 bean.xml
<!--配置dao-->
<bean id="accountDao" class="com.greyson.dao.impl.AccountDaoImpl">
<!--注入runner-->
<property name="runner" ref="runner"></property>
</bean>
<!--配置runner-->
<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://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="HotteMYSQL"></property>
</bean>
基于注解的IOC实例
1、Spring 中的新注解:
@Configuration
- 作用:指定当前类是一个配置类
- 细节:当配置类作为 AnnotationConfigurationApplicationContext
对象创建的参数时,该注解可以不写
@ComponentScan
-
作用:用于通过注解指定 Spring 在创建容器时要扫描的包
-
属性:
value : 它和 basepackages 的作用是一样的,都是用于指定创建容器时要扫描的包
使用此注解就等同于在 xml 中配置了:
<context:component-scan base-package="com.greyson"></context:component-scan>
@Bean
-
作用:用于把当前方法的返回值作为 bean 对象放入 Spring 的IOC容器中
-
属性:
name : 用于指定 bean 的 id,当不写时,默认值为当前方法的名称
-
细节:
当我们使用注解配置方法时,如果方法有参数,Spring 框架会去容器中查找有没有可用的 bean 对象,
查找的方式和 Autowired 注解的作用是一样的
@Import
-
作用:用于导入其他的配置类
-
属性:
value : 用于指定其他配置类的字节码
当我们使用 Import 的注解之后,有 Import 注解的类就是父配置类,而导入的都是子配置类
@Properties
-
作用:用于指定 properties 文件的位置
-
属性:
value : 指定文件的名称和路径
-
关键字:classpath , 表示类路径下
重复代码较多,配置类如下所示:
/**
* spring的配置类,相当于bean.xml
*/
@Configuration //声明该类是个配置类
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement //事务管理的声明
public class SpringConfiguration {
}