• spring_注解笔记


    spring使用注解开发

    1.前提

    步骤1:
    要使用注解开发,就必须要保证AOP包的导入
    在这里插入图片描述
    步骤2:
    xml文件添加context约束
    步骤3:
    配置注解的支持

    
    <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:annotation-config/>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    步骤4:
    添加扫描包的支持
    指定要扫描的包,这个包下的注解就会生效。

    1 Bean

    @Component 组件,放在类上,说明这个类被spring管理了,就是Bean

    edge:

    package com.wq.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class User {
        @Value("光头强")
        private String name;
        private int age;
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2 属性注入

    @Value 用于属性的注入,相当于

    3 衍生的注解

    @Componet有几个衍生注解,我们在web开发时,会按照MVC三层架构分层。

    1. DAO层 --> @Repository
    2. Service层 --> @Service
    3. Controller层 --> @Controller

    这四个注解功能都是一样的,代表将某个类注册到Spring中,装配Bean

    4.自动装配

    1.@Autowired

    1. @Autowired 可以直接在属性上用 默认byType方式
    2. 使用@Autowired可以不用编写set方法
    3. 如果自动装配的环境较为复杂,自动装配无法通过一个@Autowired注解完成的时候我们可以添加一个@Qualifier(value = "dog1")注解来配合指定唯一的Bean对象注入

    2.@Resource

    @Resource也能实现自动装配,但不是spring的注解,是jdk自带的注解,jdk8后取消了

    @Autowired@Resource区别

    1. 都是用来自动装配的,都可以放在属性字段上面。
    2. @Autowired通过byType实现,而且必须要求这个对象存在,常用
    3. @Resource默认通过byName方式实现,如果找不到名字,就会通过byType实现,常用
    4. 执行顺序不同: @Autowired通过byType方式实现,@Resource默认通过byName方式实现

    5 作用域

    @Scope("singleton") 放在类上

  • 相关阅读:
    xf86-video-intel源码分析2 —— README文件
    响应数据web
    Rust所有权
    python 爬虫之requests 库以及相关函数的详细介绍
    Alkyne-PEG-OH 炔烃PEG羟基Alkyne-PEG-OH 炔烃PEG羟基
    iptables和firewalld基础
    Spring笔记(一)(黑马)(Ioc基础容器)
    葡萄糖-聚乙二醇-醛基/羟基 Glucose-PEG-CHO/OH
    4.Android应用架构指南:概览
    EMC学习笔记(二)模块划分及特殊器件的布局
  • 原文地址:https://blog.csdn.net/m0_63962653/article/details/132871815