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);
    }
}
相关推荐
老王IT几秒前
Rust开发环境搭建教程
开发语言·后端·rust
武子康4 分钟前
HunyuanVideo-1.5 跑得更快,先减步数还是开缓存?
人工智能·后端·agent
chenbingjie_c11 分钟前
C++ 模板进阶:从 “会用“ 到 “懂底层“(非类型参数・特化・分离式编译)
c++·后端
vipxieliang11 分钟前
ValidX vs 正则表达式:可读性与维护性对比
java·spring boot
yunyi16 分钟前
给桌面客户端做下载加速:从「桶直接公开」到「边缘优先、源站兜底」的三代演进
前端·后端
3378018 分钟前
5分钟搞懂登录认证和授权框架Spring Security
java·spring boot
vipxieliang18 分钟前
Spring Security 6.x 实战:认证、授权与 JWT 集成
java·spring boot
world781122621 分钟前
【C++】set 和 map
java·前端·c++·set·map
学长毕设22 分钟前
基于SpringBoot的社区体育馆预约系统的设计与实现
java·spring boot·后端
霸道流氓气质24 分钟前
AI 图片管理平台:Spring AI 原生多模态、Milvus 向量语义检索与 MinIO 预签名安全管控的 React + 全栈生产级实战
人工智能·spring·milvus