• Spring(十)- Spring Bean的基本注解


    一、Spring Bean的基本注解

    Spring除了xml配置文件进行配置之外,还可以使用注解方式进行配置,注解方式慢慢成为xml配置的替代方案。我们有了xml开发的经验,学习注解开发就方便了许多,注解开发更加快捷方便。
    Spring提供的注解有三个版本:
    ⚫ 2.0时代,Spring开始出现注解
    ⚫ 2.5时代,Spring的Bean配置可以使用注解完成
    ⚫ 3.0时代,Spring其他配置也可以使用注解完成,我们进入全注解时代

    基本Bean注解,主要是使用注解的方式替代原有xml的 < bean> 标签及其标签属性的配置

    <bean id="" name="" class="" scope="" lazy-init="" init-method="" destroy-method="" 
    	abstract="" autowire="" factory-bean="" factory-method="">
    bean>
    
    • 1
    • 2
    • 3

    使用@Component 注解替代< bean>标签
    在这里插入图片描述

    可以通过@Component注解的value属性指定当前Bean实例的beanName,也可以省略不写,不写的情况下为当前类名首字母小写

    // 获取方式:applicationContext.getBean("userDao");
    @Component("userDao")
    public class UserDaoImpl implements UserDao {
    }
    
    // 获取方式:applicationContext.getBean("userDaoImpl");
    @Component
    public class UserDaoImpl implements UserDao {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用注解对需要被Spring实例化的Bean进行标注,但是需要告诉Spring去哪找这些Bean,要配置组件扫描路径

    
    <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.itheima"/>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Spring 是通过注解方式配置 < bean> 标签中的属性
    在这里插入图片描述
    使用上述注解完成UserDaoImpl的基本配置

    @Component("userDao")
    @Scope("singleton")
    @Lazy(true)
    public class UserDaoImpl implements UserDao{
    	@PostConstruct
    	public void init(){}
    	
    	@PreDestroy
    	public void destroy(){}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    由于JavaEE开发是分层的,为了每层Bean标识的注解语义化更加明确,@Component又衍生出如下三个注解:
    在这里插入图片描述

    @Repository("userDao")
    public class UserDaoImpl implements UserDao{}
    
    @Service("userService")
    public class UserServiceImpl implements UserService{}
    
    @Controller("userController")
    public class UserController {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    Python torch.nn.Module.register_forward_pre_hook用法及代码示例
    kubectl应用
    03-Kafka之基本概念
    woocommerce虚拟商品和可下载商品介绍
    基于pyqt5的Qlabel字幕滚动的简单实现方式
    读书笔记:彼得·德鲁克《认识管理》第11章 若干例外及经验教训
    对比网络层 后意识层 自回归解码 有意识的神经网络
    【回归预测-LSTM预测】基于麻雀算法优化LSTM时间序列实现预测(含前后对比)附Matlab代码
    mulesoft Module 13 quiz 解析
    无代码平台助力中山医院搭建“智慧化管理体系”,实现智慧医疗
  • 原文地址:https://blog.csdn.net/qq_36602071/article/details/127888201