Spring基于注解的IOC以及IOC的案例

使用Spring的IOC实现账户的CRUD

1.spring中ioc的常用注解
2.案例使用xml方式和注解方式实现单表的CRUD操作
			持久层技术选择:dbutils
3.改造基于注解的IOC案例,使用纯注解的方式实现
			spring的一些新注解使用
4.spring和junit整合

创建数据库

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;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

编写持久层代码

//账户的持久层接口
public interface IAccountDao {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer accountId);
    //保存
    void saveAccount(Account account);
    //更新
    void updateAccount(Account account);
    //删除
    void deleteAccount(Integer accountId);
}

编写持久层实现类

//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

编写业务层接口

//编写业务层接口
public interface IAccountService {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer accountId);
    //保存
    void saveAccount(Account account);
    //更新操作
    void updateAccount(Account account);
    //删除操作
    void deleteAccount(Integer accountId);
}

编写业务层实现类

//账户的业务层实现类
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

配置实现类

<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="org.westos.demo.service.Impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="org.westos.demo.dao.Impl.AccountDaoImpl">
        <!-- 注入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://localhost:3306/heima"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>

测试类代码

public class AccountServiceTest {
    @Test
    public void testFindAll(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
    @Test
    public void testfindOne(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345f);
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        Account account = as.findAccountById(3);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        as.deleteAccount(3);
    }
}

分析测试中的问题

通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次spring的核心容器,造成了不必要的重复代码,增加了我们
开发的工作量,这种情况,在开发中应该避免。
public class AccountServiceTest{
		//1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        as.deleteAccount(3);
}
这种方式虽然能解决问题,但是仍然需要我们自己写代码来获取容器。

基于注解的IOC配置

//配置业务层的接口类
public interface IAccountService {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer accountId);
    //保存
    void saveAccount(Account account);
    //更新操作
    void updateAccount(Account account);
    //删除操作
    void deleteAccount(Integer accountId);
}

//配置业务层的实现类
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

使用@Repository注解持久层的实现类

//账户的持久层接口
public interface IAccountDao {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer accountId);
    //保存
    void saveAccount(Account account);
    //更新
    void updateAccount(Account account);
    //删除
    void deleteAccount(Integer accountId);
}


//账户的持久层实现类
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

创建Spring的xml配制文件并开启对注解的支持

<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="org.westos.demo"></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://localhost:3306/heima"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>

常用注解

用于创建对象的
	相当于:<bean id="" class="">
	
@Component
作用:把资源让给Spring来管理,相当于在xml中配置一个bean
属性:value指定bean的id,如果不指定value的属性,默认bean的id是当前类的类名,首字母小写。

@Controller  @Service  @Respository
这三个注解都是针对一个的衍生注解,它们的作用及属性都是一模一样的。不过是提供了更加明确的语义化。
@Controller:一般用于表现层的注解
@Service:一般用于业务层的注解
@Repository:一般用于持久层的注解
细节:如果注解中有且只有一个属性要赋值时,且名称是value,value在赋值时可以不写。
--------------------------------------------------------
用于注入数据的:
	相当于:<property name="" ref="">
		   <property name="" value="">
@Autowired
作用:自动按照类型注入,当使用注解注入属性时,set方法可以省略,它只能注入其他bean类型,当有多个类型匹配时,使用
要注入的对象变量名称作为bean的id,在spring容器中查找,找到了也可以注入成功,找不到就报错。

@Qualifier
作用:在自动按照类型注入的基础之上,再按照Bean的id注入,它在给字段注入时不能独立使用,必须和@Autowire一起使用,
但是给方法参数注入时,可以独立使用。
属性:value指定bean的id

@Resource
作用:直接按照Bean的id注入,它也只能注入其它的bean类型
属性:name指定bean的id

@Value
作用:注入基本数据类型和String类型数据的
属性:value用于指定值
-------------------------------------------------------
用于改变作用范围的:
	相当于<bean id="" class="" scope="">

@Scope
作用:指定bean的作用范围
属性:value指定范围的值
	取值:singleton	prototype	request	  session	globalsession
-------------------------------------------------------
和生命周期相关的:
	相当于<bean id="" class="" init-method="" destroy-method="">
@PostConstruct
作用:用于指定初始化方法

@PreDestroy
作用:用于指定初始化方法

@PreDestroy
作用:用于指定销毁方法

关于Spring注解和XML的选择问题

注解的优势:
	配置简单,维护方便(我们找到类,就相当于找到了对应的配置)
XML的优势:
	修改时,不用源代码,不涉及重新编译和部署

Spring管理Bean方式的比较

基于XML配置基于注解配置
Bean定义@Component衍生类 @Repository @Service @Controller
Bean名称通过id或者name指定@Component(“person”)
Bean注入或者通过P命名空间@Autowired按类型注入 @Qualifier按名称注入
生命过程,Bean作用范围init-method destroy-method范围scope属性@PostConstrut初始化 @PreDestroy销毁 @Scope设置作用范围
适合场景Bean来自第三方,使用其他Bean的实现类由用户自己开发

Spring的纯注解配置

我们发现,我们之所以离不开xml配置,是因为配置文件中有一句很关键的配置:
<context:component-scan base-package="org.westos.demo"></context:component-scan>
如果它要能够也使用注解,那么我们就离脱离xml文件又进了一步。

另外,数据源和JdbcTemplate的配置也需要靠注解来实现。
<!--配置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://localhost:3306/heima"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

新注解说明

@Configuration
作用:用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用
AnnotationApplicationContext(有@Configuration注解的类.class)
属性:value:用于指定配置类的字节码
@Configuration
@ComponentScan("org.westos.demo")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

@ComponentScan
作用:用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中一样:
<context:component-scan base-package="org.westos.demo"/>
属性:basePackages:用于指定要扫描的包,和该注解中的value属性作用一样。

@Bean
作用:该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器
属性:name给当前@Bean注解方法创建的对象指定一个名称(即bean的id)

使用以上三个注解,我们已经把数据源和扫描的包从配制文件中移除了,此时就可以删除bean.xml文件了,但是由于没有了配置
文件,创建数据源的配置又都写死在类中了,我们可以使用下一个注解配置出来:
@PropertySource
作用:用于加载.properties文件中的配置,例如我们配置数据源时,可以把连接数据库的信息写到Properties配置文件中,就
可以使用此注解指定properties配置文件的位置。
属性:value[]:用于指定properties文件的位置,如果是在类路径下,需要写上classpath:

@Import
作用:用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解,当然,写上也没问题。
属性:value[]:用于指定其他配置类的字节码。

Spring整合Junit

在测试类中,每个测试方法都有以下两行代码:
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

	针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,
问题也就解决了。
	我们都知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓
我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们
替换掉它的运行器。这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。
我们只需要告诉它配置文件在哪就行了。

配置步骤

第一步:拷贝整合Junit的必备jar包到pom.xml文件中

第二步:使用@RunWith注解替换原有运行器

@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}

第三步:使用@ContextConfiguration指定Spring配置文件的位置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}

@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

第四步:使用@Autowired给测试类中的变量注入数据

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
	@Autowired
	private IAccountService as:  
}

为什么不把测试类配到xml文件中?
(1)当我们在xml中配置了一个bean,spring加载配置文件创建容器时,就会创建对象。
(2)测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有
使用,那么存在容器中就会造成资源的浪费。
所以基于以上两点:我们不应该把测试配置到xml文件中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值