Spring中的IoC(4)
基于xml的IoC案例
public interface AccountDAO {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 通过id查询所有
*
* @param id
* @return
*/
Account findAccountById(int id);
/**
* 保存数据
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 通过id删除
* @param id
*/
void deleteById(int id);
}
public class AccountDAOImpl implements AccountDAO {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
@Override
public List<Account> findAllAccount() {
List<Account> accountList = null;
try {
String sql = "select * from account";
accountList = runner.query(sql, new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
return accountList;
}
@Override
public Account findAccountById(int id) {
Account account = null;
try {
String sql = "select * from account where id = ?";
account = runner.query(sql, new BeanHandler<Account>(Account.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
@Override
public void saveAccount(Account account) {
try {
String sql = "insert into account(name,money)values(?,?)";
runner.update(sql,account.getName(),account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void updateAccount(Account account) {
try {
String sql = "update account set name=?,money=? where id =?";
runner.update(sql,account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deleteById(int id) {
try {
String sql = "delete from account where id =?";
runner.update(sql,id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class Account {
private int id;
private String name;
private float money;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
public interface AccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 通过id查询所有
*
* @param id
* @return
*/
Account findAccountById(int id);
/**
* 保存数据
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 通过id删除
* @param id
*/
void deleteById(int id);
}
public class AccountServiceImpl implements AccountService {
private AccountDAO accountDAO;
public void setAccountDAO(AccountDAO accountDAO) {
this.accountDAO = accountDAO;
}
@Override
public List<Account> findAllAccount() {
return accountDAO.findAllAccount();
}
@Override
public Account findAccountById(int id) {
return accountDAO.findAccountById(id);
}
@Override
public void saveAccount(Account account) {
accountDAO.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDAO.updateAccount(account);
}
@Override
public void deleteById(int id) {
accountDAO.deleteById(id);
}
}
<?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.toulan.service.impl.AccountServiceImpl">
<!--注入DAO-->
<property name="accountDAO" ref="accountDAO"></property>
</bean>
<!--配置Dao对象-->
<bean id="accountDAO" class="com.toulan.dao.impl.AccountDAOImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
<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/springdemo"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
public class AccountServiceTest {
@Test
public void testFindAll() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService) ac.getBean("accountService");
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
@Test
public void testFindOne() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService) ac.getBean("accountService");
//3.执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService) ac.getBean("accountService");
Account account = new Account();
account.setName("test");
account.setMoney(12345f);
//3.执行方法
as.saveAccount(account);
}
@Test
public void testUpdate() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService) ac.getBean("accountService");
//3.执行方法
Account account = as.findAccountById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService) ac.getBean("accountService");
//3.执行方法
as.deleteById(4);
}
}
基于注解的IoC案例
注解 | 作用 | 属性 |
---|---|---|
@Configuration | 指定当前类是一个配置类 | 无 |
@ComponentScan | 用于通过注解指定spring在创建容器时要扫描的包 | 它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。我们使用此注解就等同于在xml中配置了:<context:component-scan base-package=“com.toulan”></context:component-scan> |
@Bean | 用于把当前方法的返回值作为bean对象存入spring的ioc容器中 | name:用于指定bean的id。当不写时,默认值是当前方法的名称 |
@Import | 用于导入其他的配置类 | 用于指定其他配置类的字节码。当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类 |
@PropertySource | 用于指定properties文件的位置 | value:指定文件的名称和路径。关键字:classpath,表示类路径下 |
@Configuration的细节:细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
@Bean的细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。查找的方式和Autowired注解的作用是一样的
代码如下:
public interface AccountDAO {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 通过id查询所有
*
* @param id
* @return
*/
Account findAccountById(int id);
/**
* 保存数据
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 通过id删除
* @param id
*/
void deleteById(int id);
}
@Repository("accountDAO")
public class AccountDAOImpl implements AccountDAO {
@Autowired
private QueryRunner runner;
@Override
public List<Account> findAllAccount() {
List<Account> accountList = null;
try {
String sql = "select * from account";
accountList = runner.query(sql, new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
return accountList;
}
@Override
public Account findAccountById(int id) {
Account account = null;
try {
String sql = "select * from account where id = ?";
account = runner.query(sql, new BeanHandler<Account>(Account.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
@Override
public void saveAccount(Account account) {
try {
String sql = "insert into account(name,money)values(?,?)";
runner.update(sql,account.getName(),account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void updateAccount(Account account) {
try {
String sql = "update account set name=?,money=? where id =?";
runner.update(sql,account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deleteById(int id) {
try {
String sql = "delete from account where id =?";
runner.update(sql,id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class Account {
private int id;
private String name;
private float money;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
public interface AccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 通过id查询所有
*
* @param id
* @return
*/
Account findAccountById(int id);
/**
* 保存数据
* @param account
*/
void saveAccount(Account account);
/**
* 修改
* @param account
*/
void updateAccount(Account account);
/**
* 通过id删除
* @param id
*/
void deleteById(int id);
}
/**
* @Author LOL_toulan
* @Time 2020/2/4 11:18
* @Message
*
* 该类是一个配置类,它的作用和bean.xml是一样的
* spring中的新注解
* Configuration
* 作用:指定当前类是一个配置类
* 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
* 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注解的作用是一样的
* Import
* 作用:用于导入其他的配置类
* 属性:
* value:用于指定其他配置类的字节码。
* 当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
* PropertySource
* 作用:用于指定properties文件的位置
* 属性:
* value:指定文件的名称和路径。
* 关键字:classpath,表示类路径下
*/
@ComponentScan("com.loltoulan")
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@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
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean
public DataSource createDAtaSource(){
ComboPooledDataSource ds = null;
try {
ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return ds;
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdemo
jdbc.username=root
jdbc.password=root
/**
* 使用Junit单元测试:测试我们的配置
* Spring整合junit的配置
* 1、导入spring整合junit的jar(坐标)
* 2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
* @Runwith
* 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
* @ContextConfiguration
* locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
* classes:指定注解类所在地位置
*
* 当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
AccountService as;
@Test
public void testFindAll() {
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
@Test
public void testFindOne() {
//3.执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("test");
account.setMoney(12345f);
//3.执行方法
as.saveAccount(account);
}
@Test
public void testUpdate() {
//3.执行方法
Account account = as.findAccountById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//3.执行方法
as.deleteById(4);
}
}
来源:CSDN
作者:LOL_toulan
链接:https://blog.csdn.net/LOL_toulan/article/details/104163566