Spring实现纯注解项目开发

为什么使用注解开发?

从前面的内容我们可以发现,Spring开发中有许多的配置,非常的费时费力,影响开发效率。
Spring本身就是一个轻代码而重配置的框架,配置比较繁重,影响开发效率,所以就在Spring中加入了注解,使用注解代替原来的xml配置文件,这样就可以简化配置,提升开发效率。

Spring开发中的常用注解

Bean管理类常用的四个注解(作用相同,名称不同)

注解用法
@Component使用在类上用于实例化Bean
@Controller使用在表现层类上用于实例化Bean(作用于@Component一致)
@Service使用在业务层类上用于实例化Bean(作用于@Component一致)
@Repository使用在持久层类上用于实例化Bean(作用于@Component一致)

依赖注入相关的注解(加在成员变量上)

注解用法
@Value简单类型(基本类型+字符串)
@Autowired默认按类型进行自动装配(自定义引用类型),不看引用类的注解名称
@Qualifier不能单独使用,必须和@Autowired一起使用。强制使用名称注入(选择名称为value值的对象注入)
@ResourceJava提供的注解,也可以达到强制使用名称注入的作用(此注解单独使用,使用name参数指定名称)

对象生命周期注解

注解用法
@Scope取值singleton(单例),prototype(多例)

初始化方法和销毁方法

注解用法
@PostConstruct相当于init-method 该注解作用在方法上
@PreDestroy相当于destroy-method 该注解作用在方法上

其他注解

注解用法
@Configuration声明当前类是一个配置类
@ComponentScan扫描指定的包路径
@Import用于导入其他配置类
@PropertySource用于加载.properties 文件中的配置
@Bean只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到IOC容器中
@RunWithSpring整合JUnit,可以实现简化测试的开发
@ContextConfiguration用于指定Spring 配置文件
@Test测试方法

代码示例

1. 导入Maven依赖

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 创建实体类(用于接收从数据库中查询到的信息)

package com.qcby.entity;

//Java Bean风格(属性私有,生成公共方法)
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 +
                '}';
    }
}

3. 编写Service层和Dao层查询

3.1 Service层

package com.qcby.service;

import com.qcby.entity.Account;

import java.util.List;

public interface AccountService {
    public List<Account> findAll(); //查询所有账号
}
package com.qcby.service.impl;

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

import java.util.List;

@Service("as")
public class AccountServImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

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

3.2 Dao层

package com.qcby.dao;

import com.qcby.entity.Account;

import java.util.List;

public interface AccountDao {
    public List<Account> findAll(); //查询所有账号
}
package com.qcby.dao.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository("ad")
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private DruidDataSource druidDataSource;

    public List<Account> findAll() {
        //定义数据库对象
        DruidPooledConnection 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;
    }
}

4. 创建配置类(代替xml配置文件)

package com.qcby.uitl;

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;

// IOC纯注解开发方式,这个类可以代替配置文件
@Configuration //声明当前类是一个配置类
@ComponentScan("com.qcby")//扫描指定的包路径
//如果存在两个配置文件,则需要两个配置类
//@Import(SpringConfig2.class)
public class SpringConfig {
    //要想通过纯注解开发方式进行开发,就需要解决第三方类的注解标记问题
    //比如调用了Alibaba的连接池类需要注入,你不能直接去修改Alibaba的源码去加注解
    //@Bean 只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到IOC容器中
    @Bean()
    public DruidDataSource createDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("localhost");
        druidDataSource.setUsername("admin");
        druidDataSource.setPassword("666");
        return druidDataSource;
    }
}

5. 在配置文件中开启注解扫描

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

    <!--  注解开发方式  -->
    <!--  重点是开启注解扫描  -->
    <context:component-scan base-package="com.qcby.service"/>
    <context:component-scan base-package="com.qcby.entity"/>
</beans>

6. 创建测试类进行测试

import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
import com.qcby.service.AccountService;
import com.qcby.uitl.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


// spring整合junit纯注解开发
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class) //加载配置类
public class AccountServiceTest {
    @Autowired
    private AccountService as;

    @Test
    public void run() {
        List<Account> all = as.findAll();
        for (Account a : all) {
            System.out.println(a);
        }
    }
}
  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值