简单Spring学习笔记(二)

14 篇文章 0 订阅
6 篇文章 0 订阅

概述

今天的知识为Spring的相关注解开发以及利用Spring实现对数据库的增删改查。如你对Spring的基本概念还不熟悉,可以先去看看Spring第一天的基础内容:简单Spring学习笔记(一)

在Spring的配置方式其实是有注解配置和xml的方式的,这两者的方式各不相同,都能够降低代码的耦合度,只是配置方式不一样。

用于创建对象的注解

相当于:<bean id="“class=”">
@Component:

作用:
	把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
属性:
	value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

@Controller @Service @Repository:

@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

Spring中的新注解

@Configuration

作用:
用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(@Configuration 注解类.class)。
属性:
value:用于指定配置类的字节码

@ComponentScan

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

@Bean

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

@PropertySource

作用:
	用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到
properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
属性:
	value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

案例-使用IOC实现对数据库的CRUD

案例说明:
使用IOC的注解模式实现对账户数据库的增删改查。
开发环境:
开发工具:IntelliJ IDEA 如未激活请看:IDEA的激活方法
数据库环境:这里使用mysql 5.5(尽量一致,5.7也可以)
Maven版本:这里使用3.5.2,如未安装、配置请看:Maven的安装及配置
jdbc工具:使用dbutils

环境搭建

1.创建数据库spring01和account表

create database spring01;
use spring01;
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.创建Maven新项目取名:day02_Spring,导入相关jar的坐标。

<packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>

在这里插入图片描述
3.创建Acount实体类,设置三个属性分别对应数据库的数据,生成get和set方法,同时生成toString方法。

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

在这里插入图片描述

4.创建业务层Service接口和实现类,设置findAllAccount、findAccountByid、saveAccount、updateAccount、deleteAccount方法,并在实现类里实现相关方法。
AccountService接口

public interface AccountService {
    /**
     * 查询所有
     *
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     */
    Account findAccountByid(Integer id);

    /**
     * 保存
     */
    void  saveAccount(Account account);

    /**
     * 更新
     */
    void  updateAccount(Account account);

    /**
     * 删除
     */
    void deleteAccount(Integer id);
}

AccountServiceImpl实现类

public class AccountServiceImpl implements AccountService {
    public List<Account> findAllAccount() {
        return null;
    }

    public Account findAccountByid(Integer id) {
        return null;
    }

    public void saveAccount(Account account) {

    }

    public void updateAccount(Account account) {

    }

    public void deleteAccount(Integer id) {

    }
}

在这里插入图片描述
5.创建持久层及实现类,这里使用dbutils。
dao接口

public interface AccountDao {
    /**
     * 查询所有
     *
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     */
    Account findAccountByid(Integer id);

    /**
     * 保存
     */
    void  saveAccount(Account account);

    /**
     * 更新
     */
    void  updateAccount(Account account);

    /**
     * 删除
     */
    void deleteAccount(Integer id);
}

dao实现类

   @Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private QueryRunner runner;



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

    public Account findAccountByid(Integer id) {
        try {
            return runner.query("select *from account where id = ?",new BeanHandler<Account>(Account.class),id);
        } catch (Exception e) {
            throw  new  RuntimeException(e);
        }
    }

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

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

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

环境搭建已经完成,现在可以开始使用注解开发了。

使用注解的方式实现CRUD

1.创建bean.xml

<?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">
</beans>

2.在AccountServiceImpl添加注解:

@Service("accountService")

在这里插入图片描述
3.在AccountDaoImpl添加注解

@Repository("accountDao")
@Autowired

在这里插入图片描述
4.定义一个配置类SpringConfiguration类,替代bean.xml

@Configuration
@ComponentScan("Pale")
public class SpringConfiguration {
    @Bean("runner")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring01");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException();
        }


    }
}

在这里插入图片描述
5.编写一个测试类来测试功能:

public class AccountTest {
    @Test
    public void testFindAll(){
        //获取容器
        //  ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

        //获取service对象
        AccountService accountService = (AccountService)ac.getBean("accountService");
        List<Account> allAccount = accountService.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //获取service对象
        AccountService service = (AccountService)ac.getBean("accountService");
        Account accountByid = service.findAccountByid(1);
        System.out.println(accountByid);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("test 133");
        account.setMoney(143334f);
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //获取service对象
        AccountService service = (AccountService)ac.getBean("accountService");
        service.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //获取service对象
        AccountService service = (AccountService)ac.getBean("accountService");
        Account accountByid = service.findAccountByid(4);
        accountByid.setMoney(23555f);
        service.updateAccount(accountByid);
    }
    @Test
    public void testDelete(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //获取service对象
        AccountService service = (AccountService)ac.getBean("accountService");
        service.deleteAccount(4);
    }

}

试运行查询所有方法,如果以前顺利的话将查询出该表的所有数据。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值