spring_注解开发

注解驱动的意义

什么是注解驱动

  • 注解启动时使用注解的形式替代xml配置,将繁杂的spring配置文件从工程中彻底消除掉,简化书写

注解驱动的弊端

  • 为了达成注解驱动的目的,可能会将原先很简单的书写,变的更加复杂
  • XML中配置第三方开发的资源是很方便的,但使用注解驱动无法在第三方开发的资源中进行编辑,因此会增大开发工作量

在这里插入图片描述

常用注解

启动注解功能

  • 启动注解扫描,加载类中配置的注解项
    在spring核心配置文件中添加如下标签:
    在这里插入图片描述
  • 说明
    ◆ 在进行包所扫描时,会对配置的包及其子包中所有文件进行扫描
    ◆ 扫描过程是以文件夹递归迭代的形式进行的
    ◆ 扫描过程仅读取合法的java文件
    ◆ 扫描时仅读取spring可识别的注解
    ◆ 扫描结束后会将可识别的有效注解转化为spring对应的资源加入IoC容器
  • 注意
    ◆ 无论是注解格式还是XML配置格式,最终都是将资源加载到IoC容器中,差别仅仅是数据读取方式不同
    ◆ 从加载效率上来说注解优于XML配置文件

bean的定义

  • 名称:@Component @Controller @Service @Repository
  • 类型:类注解
  • 位置:类定义上方
  • 作用:设置给类为spring管理的bean
  • 范例:在这里插入图片描述
  • 说明:
    ◆ @Controller、@Service、@Repository是@Component的衍生注解,功能同@Component
  • 相关属性:
    ◆ value(默认):定义bean的访问id

代码演示

spring核心配置文件:

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

</beans>

注解写在类上方:

@Component
public class User {

}

main方法测试:

public class Demo {
    public static void main(String[] args) {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = ctx.getBean(User.class);
        System.out.println(user);
    }
}

测试结果:
在这里插入图片描述

bean的作用域

  • 名称:@Scope
  • 类型:类注解
  • 位置:类定义上方
  • 作用:设置该类作为bean对应的scope属性
  • 范例:在这里插入图片描述
  • 相关属性:
    ◆ value(默认):定义bean的作用域,默认为singleton

bean的生命周期

  • 名称:@PostConstruct、@PreDestroy
  • 类型:方法注解
  • 位置:方法定义上方
  • 作用:设置该类作为bean对应的生命周期方法
  • 范例:在这里插入图片描述

小节

  • 开启注解驱动
  • bean的四种注解定义格式
  • bean相关属性注解格式
    ◆ id
    ◆ class
    ◆ scope
    ◆ init-method
    ◆ destrop-method

加载第三方资源

  • 名称:@Bean
  • 类型:方法注解
  • 位置:方法定义上方
  • 作用:设置该方法的返回值作为spring管理的bean
  • 范例:在这里插入图片描述
  • 说明:
    ◆ 因为第三方bean无法在其源码上进行修改,使用@Bean解决第三方bean的引入问题
    ◆ 该注解用于替代XML配置中的静态工厂与实例工厂创建bean,不区分方法是否为静态或非静态
    ◆ @Bean所在的类必须被spring扫描加载,否则该注解无法生效
  • 相关属性
    ◆ value(默认):定义bean的访问id

代码演示

定义类:

@Component
public class JdbcConfig {
    @Bean("dataSource")
    public DruidDataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://129.168.23.129:3306/spring_db");
        ds.setUsername("root");
        ds.setPassword("itheima888");
        return ds;
    }
}

main方法测试:

public class Demo {
    
    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        DruidDataSource bean = (DruidDataSource) ctx.getBean("dataSource");
        System.out.println(bean);

    }
}

测试结果:
在这里插入图片描述

bean的非引用类型属性注入

  • 名称:@Value
  • 类型:属性注解,方法注解
  • 位置:属性定义上方,方法定义上方
  • 作用:设置对应属性的值或对方法进行传参
  • 范例:在这里插入图片描述
  • 说明:
    ◆ value值仅支持非引用类型数据,赋值时对方法的所有参数全部赋值
    ◆ value值支持读取properties文件中的属性值,通过类属性将properties中数据传入类中
    ◆ value值支持SpEL
    ◆ @value注解如果添加在属性上方,可以省略set方法(set方法的目的是为属性赋值)
  • 相关属性
    ◆ value(默认):定义对应的属性值或参数值

bean的引用类型属性注入

  • 名称:@Autowired、@Qualifier
  • 类型:属性注解,方法注解
  • 位置:属性定义上方,方法定义上方
  • 作用:设置对应属性的对象或对方法进行引用类型传参
  • 范例:在这里插入图片描述
  • 说明:
    ◆ @Autowired默认按类型装配,指定@Qualifier后可以指定自动装配的bean的id
  • 相关属性:
    ◆ required:定义该属性是否允许为null

bean的引用类型属性优先注入

  • 名称:@Primary
  • 类型:类注解
  • 位置:类定义上方
  • 作用:设置类对应的bean按类型装配时优先装配
  • 范例:在这里插入图片描述
  • 说明:
    ◆ @Autowired默认按类型装配,当出现相同类型的bean,使用@Primary提高按类型自动装配的优先级,多个@Primary 会导致优先级设置无效

代码演示

@Component
public class User {
    @Value("cls")
    private String name;
    @Value("18")
    private int age;
    @Autowired
    private Student student;
}
public class Demo {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        User bean = (User) ctx.getBean("user");
        System.out.println(bean);

    }
}

测试结果:
在这里插入图片描述

加载Properties文件

  • 名称:@PropertySource
  • 类型:类注解
  • 位置:类定义上方
  • 作用:加载properties文件中的属性值
  • 范例:在这里插入图片描述
  • 说明:
    ◆ 不支持*通配格式,一旦加载,所有spring控制的bean中均可使用对应属性值
  • 相关属性:
    ◆ value(默认):设置加载的properties文件名
    ◆ ignoreResourceNotFound:如果资源未找到,是否忽略,默认为false

代码演示

properties文件:

jdbc.userName=root
jdbc.password=itheima

Student类;

@Component
@PropertySource("classpath:jdbc.properties")
public class Student {
    @Value("${jdbc.userName}")
    private String name;
    @Value("${jdbc.password}")
    private String pwd;
}

main测试方法:

public class Demo {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student bean = (Student) ctx.getBean(Student.class);
        System.out.println(bean);

    }
}

测试结果:
在这里插入图片描述

纯注解格式

  • 名称:@Configuration、@ComponentScan
  • 类型:类注解
  • 位置:类定义上方
  • 作用:设置当前类为spring核心配置加载类
  • 范例:在这里插入图片描述
  • 说明:
    ◆ 核心配置类用于替换spring核心配置文件,此类可以设置空的,不设置变量与属性
    ◆ bean扫描工作使用注解@ComponentScan替代

AnnotationConfigApplicationContext

  • 加载纯注解格式上下文对象,需要使用AnnotationConfigApplicationContext
    在这里插入图片描述

第三方bean配置与管理

  • 名称:@Import
  • 类型:类注解
  • 位置:类定义上方
  • 作用:导入第三方bean作为spring控制的资源
  • 范例:在这里插入图片描述
  • 说明:
    ◆ @Import注解在同一个类上,仅允许添加一次,如果需要导入多个,使用数组的形式进行设定
    ◆ 在被导入的类中可以继续使用@Import导入其他资源(了解)
    ◆ @Bean所在的类可以使用导入的形式进入spring容器,无需声明为bean

bean加载控制

@DependsOn 依赖加载

  • 名称:@DependsOn
  • 类型:类注解,方法注解
  • 位置:bean定义的位置(类上或方法上)
  • 作用:控制bean的加载顺序,使其在指定bean加载完毕后再加载
  • 范例:在这里插入图片描述
  • 说明:
    ◆ 配置在方法上,使@DependsOn指定的bean优先于@Bean配置的bean进行加载
    ◆ 配置在类上,使@DependsOn指定的bean优先于当前类中所有@Bean配置的bean进行加载
    ◆ 配置在类上,使@DependsOn指定的bean优先于@Component等配置的bean进行加载
  • 相关属性:
    ◆ value(默认):设置当前bean所依赖的bean的id

@Order 依赖加载

  • 名称:@Order
  • 类型:配置类注解
  • 位置:配置类定义的位置(类上)
  • 作用:控制配置类的加载顺序
  • 范例:在这里插入图片描述

@Lazy 依赖加载

  • 名称: @Lazy
  • 类型:类注解,方法注解
  • 位置:bean定义的位置(类上或方法上)
  • 作用:控制bean的加载时机,使其延迟加载
  • 范例:在这里插入图片描述

依赖加载应用场景

  • @DependsOn
    ◆微信订阅号,发布消息和订阅消息的bean的加载顺序控制
    ◆双11活动期间,零点前是结算策略A,零点后是结算策略B,策略B操作的数据为促销数据。策略B 加载顺序与促销数据的加载顺序
  • @Lazy
    ◆程序灾难出现后对应的应急预案处理是启动容器时加载时机
  • @Order
    ◆多个种类的配置出现后,优先加载系统级的,然后加载业务级的,避免细粒度的加载控制

整合第三方技术

综合案例注解开发版

在这里插入图片描述

注解整合MyBatis分析

  • 业务类使用注解形式声明bean,属性采用注解注入
  • 建立独立的配置管理类,分类管理外部资源,根据功能进行分类,并提供对应的方法获取bean
  • 使用注解形式启动bean扫描,加载所有注解配置的资源(bean)
  • 使用AnnotationConfigApplicationContext对象加载所有的启动配置类,内部使用导入方式进行关联

注解整合MyBatis步骤

  1. 修改mybatis外部配置文件格式为注解格式
  2. 业务类使用@Component声明bean,使用@Autowired注入对象
  3. 建立配置文件JDBCConfig与MyBatisConfig类,并将其导入到核心配置类SpringConfig
  4. 开启注解扫描
  5. 使用AnnotationConfigApplicationContext对象加载配置项

综合案例代码演示

整体结构:
在这里插入图片描述

maven的pom文件:

<?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.itheima</groupId>
    <artifactId>Spring_day02_02_注解整合MyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

    </dependencies>
</project>

properties文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.23.129:3306/spring_db
jdbc.username=root
jdbc.password=itheima888

dao层:

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.*;
import org.mybatis.spring.SqlSessionFactoryBean;

import java.util.List;

public interface AccountDao {

    @Insert("insert into account(name,money) values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from account where id = #{id}")
    void delete(Integer id);

    @Update("update account set name=#{name},money=#{money} where id=#{id}")
    void update(Account account);

    @Select("select * from account where id=#{id}")
    Account findById(Integer id);

    @Select("select * from account")
    List<Account> findAll();
}

domain实体类:

package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

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

service层接口:

package com.itheima.service;

import com.itheima.domain.Account;

import java.util.List;

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}

service层实现:

package com.itheima.service.impl;


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

import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void save(Account account) {
        accountDao.save(account);
    }

    public void delete(Integer id) {
        accountDao.delete(id);
    }

    public void update(Account account) {
        accountDao.update(account);
    }

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

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }
}

JDBC配置类:

package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
@Component
public class JDBCConfig {
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String userName;

    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

MyBatis配置类:

package com.itheima.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.itheima.domain");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }
    
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }

}

spring核心配置类:

package com.itheima.config;

import org.springframework.context.annotation.*;


@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JDBCConfig.class,MyBatisConfig.class})
public class SpringConfig{

}

测试类:

import com.alibaba.druid.pool.DruidDataSource;
        import com.itheima.config.SpringConfig;
        import com.itheima.domain.Account;
        import com.itheima.service.AccountService;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.annotation.AnnotationConfigApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = (AccountService) ctx.getBean("accountService");
        Account ac = accountService.findById(2);
        System.out.println(ac);


    }
}

测试结果:
在这里插入图片描述

注解整合Junit

如何在Junit中使用spring中的资源?

  • Spring接管Junit的运行权,使用Spring专用的Junit类加载器

  • 为Junit测试用例设定对应的spring容器

  • 注意:
    ◆ 从Spring5.0以后,要求Junit的版本必须是4.12及以上
    ◆ Junit仅用于单元测试,不能将Junit的测试类配置成spring的bean,否则该配置将会被打包进入工 程中

  • 导入Spring整合Junit坐标
    在这里插入图片描述

  • Spring整合Junit测试用例注解格式
    在这里插入图片描述

代码演示

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void test(){
        List<Account> all = accountService.findAll();
        System.out.println(all);
    }

}

测试结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值