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);
    }
}
相关推荐
掘金码甲哥24 分钟前
超性感的轻量级openclaw平替,我来给你打call
后端
用户8356290780514 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
啊哈灵机一动4 小时前
使用golang搭建一个nes 模拟器
后端
日月云棠5 小时前
各版本JDK对比:JDK 25 特性详解
java
间彧5 小时前
SpringBoot + ShardingSphere 读写分离实战指南
后端
砍材农夫5 小时前
订单超时
后端
树獭叔叔5 小时前
06-大模型如何"学习":从梯度下降到AdamW优化器
后端·aigc·openai
用户8307196840825 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
得鹿5 小时前
MySQL基础架构与存储引擎、索引、事务、锁、日志
后端
程序员飞哥5 小时前
Block科技公司裁员四千人,竟然是因为 AI ?
人工智能·后端·程序员