Spring之注解开发

1.使用Java类代替xml配置文件

在自定义的Java类上加@Configuration注解,表示设定当前类为配置类

java 复制代码
package config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
}

2.使用@Component注解定义bean

(1)在相应的Java类上加@Component注解,表示这是一个bean

java 复制代码
package domain;

import org.springframework.stereotype.Component;

@Component
public class Animal {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

注:单独使用@Component注解相当于在xml文件只写了<bean>标签的class属性,@Component("animal")相当于在xml文件写了<bean>标签的id和class两个属性
(2)Spring提供了@Component注解的三个衍生注解

  • @Controller用于表现层bean定义
  • @Service用于业务层bean定义
  • @Repository用于数据层bean定义

3.使用@ComponentScan注解使配置类能扫描到定义的bean

在配置类上加@Configuration注解,使其能扫描到定义的bean

java 复制代码
@Configuration
@ComponentScan("com.example.domain")
public class SpringConfig {
}

注:@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个路径需使用数组格式

java 复制代码
@ComponentScan({"com.example.service","com.example.domain"})

4.通过AnnotationConfigApplicationContext类获取IoC容器

java 复制代码
import config.SpringConfig;
import domain.Animal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Demo {
    public static void main(String[] args) {
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Animal animal = ctx.getBean(Animal.class);
        System.out.println(animal);
    }
}
相关推荐
陈随易1 分钟前
MoonBit 2026 深圳线下交流分享
前端·后端·程序员
玖米GEO运营王总监8 分钟前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
HarmonSir1 小时前
Octop 架构解析(外番篇):两种多 Agent 协作,Octop 群聊房间 vs dsh 工单授权
后端·架构
tong_li1 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(七):给工具循环上保险
后端·langchain
AI人工智能+电脑小能手1 小时前
集合按大小切片分批,这个Java工具类5个方法含基本类型数组
java·工具类·批量处理·集合分片·分批调用
bai2731 小时前
13 个文件名里 4 个打不开:Node 能建、cmd 和 PowerShell 却读不了
javascript·后端
用户298698530142 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api
AAA修煤气灶刘哥2 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
SimonKing2 小时前
高星红果短剧的TV版|桌面版都在这里了
java·后端·程序员
用户69371750013842 小时前
AI 用久了,我发现自己越来越不想找人聊天了
前端·后端·github