SSM框架系列之如何纯注解开发

目录

一、什么是注解

二、准备工作

IOC配置文件开发的示例

三、IOC注解式开发

四、IOC纯注解式开发


一、什么是注解

  • 注解就是一种特殊的标记方式

  • 注解的格式一般为:@+注解名称("内容")

  • 注解可以作用在类、方法和属性上。

  • 传统的xml方式开发比较繁琐,代码可读性查,理解代码需要结合xml文件才能理解,而注解的作用就是简化甚至代替xml的开发方式。

接下来通过传统配置方式开发注解式开发纯注解方式开发的方式仔细聊一聊。

二、准备工作

(1)在父项目中新建一个 Module 并在其中创建一个名为 SpringDeom02 的maven子项目。

(2)在新建的springDemo_02中的pom文件中加入坐标依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
​
<!-- 连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
<!-- mysql驱动包-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

创建数据库:

create database spring_db;
use spring_db;
create table account(
id int primary key auto_increment,
name varchar(40),
money double
)character set utf8 collate utf8_general_ci;
INSERT INTO `account` VALUES ('1', '老王', '1000');
INSERT INTO `account` VALUES ('2', '小王', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

​​

在子项目的在entity包下新建Account类,与数据库中的account相对应

public class Account {
    private int id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }
​
    public void setMoney(Double money) {
        this.money = money;
    }
​
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}
​

IOC配置文件开发的示例

配置dao层

在dao层下新建接口AccountDao,新建包impl,在impl下新建类AccountDaoImpl,重写findAll方法

public interface AccountDao {
    //查询所有账号
    public List<Account> findAll() ;
}


package com.zcm.javaClass.Dao.impl;
​
import com.alibaba.druid.pool.DruidDataSource;
import com.zcm.javaClass.Dao.AccountDao;
import com.zcm.javaClass.entity.Account;
​
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
​
public class AccountDaoImpl implements AccountDao {
    private DruidDataSource druidDataSource;
​
    public void setDruidDataSource(DruidDataSource druidDataSource) {
        this.druidDataSource = druidDataSource;
    }
​
    @Override
    public List<Account> findAll(){
        //创建连接池
//        DruidDataSource druidDataSource = new DruidDataSource();
//        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
//        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_db");
//        druidDataSource.setUsername("root");
//        druidDataSource.setPassword("2020");
​
        //创建数据库对象
        Connection connection=null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Account> list = new ArrayList<Account>();
        //获取连接
        try {
            connection = druidDataSource.getConnection();
​
​
            //编写sql
            String sql = "select * from account";
            //预编译
            statement = connection.prepareStatement(sql);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                Account account = new Account();
                account.setId(resultSet.getInt("id"));
                account.setName(resultSet.getString("name"));
                account.setMoney(resultSet.getDouble("money"));
                list.add(account);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
​
​
        return list;
    }
}

配置service层

public interface AccountService {
    //查询所有账号
    public List<Account> findAll() ;
}

重写的findAll调用dao层的findAll方法,在这里注入accountDao

package com.zcm.javaClass.service.impl;
​
import com.zcm.javaClass.Dao.AccountDao;
import com.zcm.javaClass.entity.Account;
import com.zcm.javaClass.service.AccountService;
​
import java.util.List;
​
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
​
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
​
    @Override
    public List<Account> findAll() {
​
        return accountDao.findAll();
    }
}

​​

完成dao层service层还有entity层之后的目录层级

配置applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
​
    <!--    连接池对象-->
    <bean id="dr" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_db"></property>
        <property name="username" value="root"></property>
        <property name="password" value="2020"></property>
    </bean>
    <!--    service层-->
    <bean id="asi" class="com.zcm.javaClass.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="adi"></property>
    </bean>
    <!--    dao层-->
    <bean id="adi" class="com.zcm.javaClass.Dao.impl.AccountDaoImpl">
        <property name="druidDataSource" ref="dr"></property>
    </bean>
​
​
</beans>

创建测试类AccountServiceTest

import com.zcm.javaClass.entity.Account;
import com.zcm.javaClass.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
import java.util.List;
​
public class AccountServiceTest {
    @Test
    public void run(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService as = (AccountService) ac.getBean("asi");
        List<Account> all = as.findAll();
​
        for (Account account:all){
            System.out.println(account);
        }
​
    }
}
​

执行结果如下:

三、IOC注解式开发

对applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
​
    <context:component-scan base-package="com"></context:component-scan>
​
​
​
    <!--    连接池对象-->
    <bean id="dr" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_db"></property>
        <property name="username" value="langfang"></property>
        <property name="password" value="langfang@2020"></property>
    </bean>
    <!--    service层-->
    <bean id="asi" class="com.zcm.javaClass.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="adi"></property>
    </bean>
    <!--    dao层-->
    <bean id="adi" class="com.zcm.javaClass.Dao.impl.AccountDaoImpl">
        <property name="druidDataSource" ref="dr"></property>
    </bean>
</beans>

eg:在加载配置文件时会扫描com包中的类,有哪些交给ioc管理

bean管理类常用的注解

bean管理类常用的4个注解(作用相同,推荐使用在不同分层上)

  1. @Component 普通的类

  2. @Controller 表现层的类

  3. @Service 业务层的类

  4. @Repository 持久层的类

新建Person类
加入注解@Component,此类交给ioc管理

package com.zcm.javaClass.entity;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component
public class Person {
    @Value("JAVA学习课堂")
    private String name;
​
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

同样的方式创建cat类,并注入Person类

package com.zcm.javaClass.entity;
​
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component
public class Car {
    @Value("更多内容请关注JAVA学习课堂")
    private String name;
​
    @Autowired
    private Person person;
​
    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", person=" + person +
                '}';
    }
}

创建测试类执行代码:

    @Test
    public void run02(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        Car car = (Car) ac.getBean("car");
        System.out.println(car);
    }

运行结果如下:

四、IOC纯注解式开发

新建工具类​:

package com.zcm.javaClass.utils;
​
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
​
//声明当前类是配置类
@Configuration
//扫描指定的包
@ComponentScan("com")
//导入其他的配置类
@Import(SpringConfig2.class)
public class SpringConfig {
    //@Bean只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到ioc容器中
    @Bean
    public DruidDataSource createDataSource(){
​
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_db");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("2020");
​
        return druidDataSource;
    }
}

public class SpringConfig2 {
}
​

配置service层和dao层

修改AccountDaoImpl类,使用注解注入,并且将类交给ioc管理

package com.zcm.javaClass.Dao.impl;
​
import com.alibaba.druid.pool.DruidDataSource;
import com.zcm.javaClass.Dao.AccountDao;
import com.zcm.javaClass.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
​
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
​
@Repository
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private DruidDataSource druidDataSource;
​
​
    @Override
    public List<Account> findAll(){
        //创建连接池
​
        //创建数据库对象
        Connection connection=null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Account> list = new ArrayList<Account>();
        //获取连接
        try {
            connection = druidDataSource.getConnection();
​
​
            //编写sql
            String sql = "select * from account";
            //预编译
            statement = connection.prepareStatement(sql);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                Account account = new Account();
                account.setId(resultSet.getInt("id"));
                account.setName(resultSet.getString("name"));
                account.setMoney(resultSet.getDouble("money"));
                list.add(account);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
​
​
        return list;
    }
}
​

修改AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
​
    @Override
    public List<Account> findAll() {
​
        return accountDao.findAll();
    }
}

创建测试类:

    @Test
    public void run03(){
​
​
        //创建工厂,加载配置类
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = (AccountService) ac.getBean("accountServiceImpl");
        System.out.println(accountService.findAll());
​
    }

运行结果如下:

​关注 JAVA学习课堂 微信公众号,获取更多学习笔记,。

回复spring 获取实例代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值