spring的基于注解的IOC

1、spring中ioc的常用注解

1.1创建maven工程加入对应的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ximu</groupId>
    <artifactId>javaframe_spring02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jcl</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>

1.2.增加一系列的配置

<?xml version="1.0" encoding="UTF-8"?>
<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="com.ximu"/>
<!--    配置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://192.168.92.131:3306/mydb2"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

</beans>

1.3.一些常用的注解

  • 1.3.1 @Component

作用:把资源让 spring 来管理。相当于在 xml 中配置一个 bean。

属性:value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

以及@Controller @Service @Repository这三个注解与它的作用是一样的,只是用来区分三层架构的

  • 1.3.2 @Autowired:用于注入数据的

作用:自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个

类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到

就报错。

  • 1.3.3@Qualifier

作用:在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和

@Autowire 一起使用;但是给方法参数注入时,可以独立使用。

属性:value:指定 bean 的 id

  • 1.3.4@Resource

作用:直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。

属性:name:指定 bean 的 id

  • 1.3.5@Value

作用:注入基本数据类型和 String 类型数据的

属性:value:用于指定值

  • 1.3.6@Scope

作用:指定 bean 的作用范围。

属性:value:指定范围的值。

取值:singleton prototype request session globalsession

2.1和生命周期相关的:(了解)

相当于:<bean id="" class="" init-method="" destroy-method="" />

2.1.1 @PostConstruct

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

2.1.2@PreDestroy

作用:用于指定销毁方法

3.1新注解说明:@Configuration

作用:用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用

AnnotationApplicationContext(有@Configuration 注解的类.class)。

属性:value:用于指定配置类的字节码

3.1.1@Configuration

作用:用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用

AnnotationApplicationContext(有@Configuration 注解的类.class)。

属性:value:用于指定配置类的字节码

3.1.2@ComponentScan

作用:用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:

<context:component-scan base-package="com.itheima"/>是一样的。

属性:basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。

3.1.3: @Bean

作用:该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。

属性:name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)

3.1.4:@PropertySource

作用:用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到

properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。

属性:value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

2、案例使用xml方式和注解方式实现单表的CRUD操作

1.实现crud操作:

1.1 创建实体类

package com.ximu.domain;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 20:34
 */
public class Account {
    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 +
                '}';
    }
}

1.2 创建Dao接口以及实现类

package com.ximu.dao;

import com.ximu.domain.Account;

import java.util.List;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 20:32
 */
public interface AccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 删除账户
     * @param id
     */
    void deleteAccount(Integer id);
}

package com.ximu.dao.impl;

import com.ximu.dao.AccountDao;
import com.ximu.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 20:41
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAll() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }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 deleteAccount(Integer id) {
        try{
            runner.update("delete from account where id=?",id);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

1.3.创建service接口以及实现类对象

package com.ximu.service;

import com.ximu.domain.Account;

import java.util.List;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 20:40
 */
public interface AccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 删除账户
     * @param id
     */
    void deleteAccount(Integer id);
}

package com.ximu.service.impl;

import com.ximu.dao.AccountDao;
import com.ximu.domain.Account;
import com.ximu.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 20:41
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

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

package com.ximu.test;

import com.ximu.domain.Account;
import com.ximu.service.AccountService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @author 惜木
 * @version 1.0
 * @date 2020/12/25 21:08
 */
public class MainTest {

    @Test
    public void findAllTest(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountService as = (AccountService) ac.getBean("accountService");
        List<Account> all = as.findAll();
        for (Account account : all) {
            System.out.println(account);
        }

    }

    @Test
    public void saveAccount(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountService as = (AccountService) ac.getBean("accountService");
        Account account = new Account();
        account.setName("张三");
        account.setMoney(125f);
        as.saveAccount(account);

    }
}

3、改造基于注解的ioc案例,使用纯注解的方式实现

3.spring的一些新注解使用

4、spring和Junit整合

1、应用程序的入口
main方法
2、junit单元测试中,没有main方法也能执行
junit集成了一个main方法
该方法就会判断当前测试类中哪些方法有 @Test注解
junit就让有Test注解的方法执行
3、junit不会管我们是否采用spring框架
在执行测试方法时,junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

posted @ 2020-12-25 21:55  码农一号111  阅读(84)  评论(0)    收藏  举报