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 小时前
SpringBoot+Vue学生宿舍管理系统源码 带部署文档
vue.js·spring boot·后端
panxianren7 小时前
Bun 1.4 的 bun test --parallel 将 4 秒的测试套件缩短到约 1 秒
java·javascript
码事漫谈8 小时前
骂AI,会让它做得更好吗?
后端
sunshine22 girl8 小时前
Java学习七 Java 项目实战2-注册业务
java·学习
陈随易9 小时前
bm2,Node.js 与 Bun 项目部署新选择
前端·后端·程序员
省钱兄--zs9 小时前
北京24小时自助健身房系统软件开发实战:从架构设计到部署指南
java·数据仓库·spring boot·小程序·需求分析
youdexiang9 小时前
Android录音软件时间关键词检索功能分析
java·人工智能
架构技术专栏10 小时前
AI Agent 框架怎么选:从一次制度查询拆出技术边界
后端·面试
sunshine22 girl10 小时前
Java学习七 Java 项目实战1-项目创建和主页面搭建
java·开发语言·学习
code2cat10 小时前
Java进阶篇之AtomicStampedReference:引用回到原值,版本戳仍能记住变化
java·cas·并发编程·aba