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);
    }
}
相关推荐
贫民窟的勇敢爷们6 小时前
SpringBoot整合AOP切面编程实战,实现日志统一记录+接口权限校验
java·spring boot·spring
candyTong6 小时前
Claude Code Agent Teams:多 Agent 协作的生命周期与实现机制
后端·架构
AC赳赳老秦6 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
迈巴赫车主7 小时前
Java基础:list、set、map一遍过
java·开发语言
灵犀学长7 小时前
基于 Spring ThreadPoolTaskScheduler + CronTrigger 实现的动态定时任务调度系统
java·数据库·spring
好家伙VCC9 小时前
【无标题】
java
小碗羊肉9 小时前
【JavaWeb | 第十一篇】文件上传(本地&阿里云OSS)
java·阿里云·servlet
吾疾唯君医9 小时前
Java SpringBoot集成积木报表实操记录
java·spring boot·spring·导出excel·积木报表·数据文件下载
Byron Loong10 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++
hexu_blog10 小时前
vue+java实现图片批量压缩
java·前端·vue.js