1、使用xml实现IOC
1)创建数据库
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);
2)编写实体类
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; }
}
3)编写持久层代码
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<Account> findAll();
}
4)持久层实现类
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>(Account.class),accountId); }
@Override
public List<Account> findAll() { return dbAssit.query("select * from account where id=?",new BeanListHandler<Account>(Account.class)); }
}
5)编写业务层代码
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<Account> findAllAccount();
}
6)业务层实现类
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<Account> findAllAccount() { return accountDao.findAll(); }
}
7)创建并编写配置文件
<?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">
</beans>
<?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">
<property name="accountDao" ref="accountDao"></property> </bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dbAssit" ref="dbAssit"></property>
</bean>
<!-- 配置dbAssit 此处我们只注入了数据源,表明每条语句独立事务-->
<bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property>
</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:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
8)使用
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); }
}
2、基于注解的IOC
A、常用注解
用于创建对象的
@Component:把资源让spring来管理。相当于在xml中配置一个bean。
@Controller:一般用于表现层的注解。
@Service:一般用于业务层的注解。
@Repository:一般用于持久层的注解。
tips:@Controller, @Service, @Repsitory为衍生注解,提供了更加明确的语义化。
用于注入数据的
@Autowired:自动按照类型注入。
@Qualifier:在自动按照类型注入的基础之上,再按照Bean的id注入。不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。
@Resource:直接按照Bean的id注入。它也只能注入其他bean类型。
@Value:注入基本数据类型和String类型数据的
用于改变作用范围的:
@Scope:指定bean的作用范围。value:指定范围的值。 取值:singleton prototype request session globalsession
和生命周期相关的:
@PostConstruct:用于指定初始化方法。
@PreDestroy:用于指定销毁方法。
新注解
@Configuration:用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)。
@ComponentScan:用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的: <context:component-scan base-package=“com.itheima”/>是一样的。
B、过程
1)创建数据库
2)编写实体类
3)编写持久层代码
4)编写业务层代码
5)业务层实现类
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; }
}
6)持久层实现类
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
}
7)创建spring的配置类
@ComponentScan("com.xuhe93")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
8) 和spring连接数据库相关的配置类
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;
@Bean(name="runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean(name="ds2")
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);
}
}
}
9) 使用
/*
使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的@Runwith
告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在地位置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as = null;
@Test
public void testFindAll() {
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
}
转载:https://blog.csdn.net/xuhe93/article/details/105779568