需求:实现账户的CRUD操作
技术要求:使用Spring的IoC实现对象的管理
使用DBAssit作为持久层的解决方案
使用c3p0数据源
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);
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id; }
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; }
}
public interface IAccountDao { /**
* 保存 * @param account */
void save(Account account);
/**
* 更新 * @param account */
void update(Account account);
/**
* 删除 * @param accountId */
void delete(Integer accountId);
/**
* 根据 id 查询 * @param accountId * @return */
Account findById(Integer accountId);
/**
* 查询所有 * @return */
List findAll();
}
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
public void setDbAssit(DBAssit dbAssit) {
this.dbAssit = dbAssit; }
@Override
public void save(Account account) {
dbAssit.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney()); }
@Override
public void update(Account account) {
dbAssit.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId()); }
@Override
public void delete(Integer accountId) {
dbAssit.update("delete from account where id=?",accountId); }
@Override
public Account findById(Integer accountId) {
**return dbAssit.query("select * from account where id=?",new BeanHandler(Account.class),accountId);** }
@Override
public List findAll() {
return dbAssit.query("select * from account where id=?",new BeanListHandler(Account.class)); }
}
public interface IAccountService {
/**
* 保存账户 * @param account */
void saveAccount(Account account);
/**
* 更新账户 * @param account */
void updateAccount(Account account);
/**
* 删除账户 * @param account */
void deleteAccount(Integer accountId);
/**
* 根据 id 查询账户 * @param accountId * @return */
Account findAccountById(Integer accountId);
/**
* 查询所有账户 * @return */
List findAllAccount();
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void saveAccount(Account account) {
accountDao.save(account); }
@Override
public void updateAccount(Account account) {
accountDao.update(account); }
@Override
public void deleteAccount(Integer accountId) {
accountDao.delete(accountId); }
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findById(accountId); }
@Override
public List findAllAccount() {
return accountDao.findAll(); }
}
public class AccountServiceTest { /**
* 测试保存 */
@Test
public void testSaveAccount() {
Account account = new Account();
account.setName("张三");
account.setMoney(100000f);
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
as.saveAccount(account); }
/**
* 测试查询一个 */
@Test
public void testFindAccountById() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
Account account = as.findAccountById(1); System.out.println(account); }
/**
* 测试更新 */
@Test
public void testUpdateAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
Account account = as.findAccountById(1);
account.setMoney(20301050f);
as.updateAccount(account); }
/**
* 测试删除 */
@Test
public void testDeleteAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
as.deleteAccount(1); }
/**
* 测试查询所有 */
@Test
public void testFindAllAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
List list = as.findAllAccount();
for(Account account : list) {
System.out.println(account);
}
}
}
上述测试类每个测试方法都重新获取了一次spring的核心容器,造成不必要的重复代码。
上述案例基于xml配置,下面介绍基于注解的配置方式
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
}
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit; }
当使用注解注入时,set方法不用写
基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。 由于我们使用了注解配置,此时不能在继承 JdbcDaoSupport,需要自己配置一个 JdbcTemplate
相当于
相当于
相当于
上述注解配置还是不能彻底脱离xml文件 <<<<<<<<<<<<<
/**
* spring 的配置类,相当于 bean.xml 文件 * /
@Configuration
public class SpringConfiguration { }
注意: 我们已经把配置文件用类来代替了,但是如何配置创建容器时要扫描的包呢?
@Configuration @ComponentScan("com.itheima")
public class SpringConfiguration { }
注意: 我们已经配置好了要扫描的包,但是数据源和 JdbcTemplate 对象如何从配置文件中移除呢?
public class JdbcConfig {
/**
* 创建一个数据源,并存入 spring 容器中 * @return */
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setUser("root");
ds.setPassword("1234");
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///spring_day02");
return ds; }
catch (Exception e) {
throw new RuntimeException(e);
} }
/**
* 创建一个 DBAssit,并且也存入 spring 容器中 * @param dataSource * @return */
@Bean(name="dbAssit")
public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource); } }
我们已经把数据源和 DBAssit 从配置文件中移除了,此时可以删除 bean.xml 了。 但是由于没有了配置文件,创建数据源的配置又都写死在类中了。如何把它们配置出来呢
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建一个数据源,并存入 spring 容器中 * @return */
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds; }
catch (Exception e) {
throw new RuntimeException(e); } }
}
jdbc.properties 文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day44_ee247_spring
jdbc.username=root
jdbc.password=1234
此时我们已经有了两个配置类,但是他们还没有关系。如何建立他们的关系呢?
@Configuration
@ComponentScan(basePackages = "com.itheima.spring")
@Import({ JdbcConfig.class})
public class SpringConfiguration { }
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig{ }
我们已经把要配置的都配置好了,但是新的问题产生了,由于没有配置文件了,如何获取容器呢?
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest { }
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest { }
@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ; }