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);
    }
}
相关推荐
NHuan^_^43 分钟前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot
Soofjan1 小时前
Go 内存回收-GC 源码1-触发与阶段
后端
shining1 小时前
[Golang]Eino探索之旅-初窥门径
后端
掘金者阿豪1 小时前
Mac 程序员效率神器:6 个我每天都在用的 Mac 工具推荐(Alfred / Paste / PixPin / HexHub / iTerm2 /)
后端
Mr_Xuhhh1 小时前
从ArrayList到LinkedList:理解链表,掌握Java集合的另一种选择
java·数据结构·链表
小村儿1 小时前
连载04-CLAUDE.md ---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
错把套路当深情1 小时前
Java 全方向开发技术栈指南
java·开发语言
han_hanker1 小时前
springboot 一个请求的顺序解释
java·spring boot·后端
2501_921649491 小时前
原油期货量化策略开发:历史 K 线获取、RSI、MACD 布林带计算到多指标共振策略回测
后端·python·金融·数据分析·restful
杰克尼1 小时前
SpringCloud_day05
后端·spring·spring cloud